JTABLE & RESIZE

Hello guys,
I'm having a little problem. I crate a JTable and I wanna resize it, fellow the width of the String in the columns, i.e, when I get a Query (many strings ditributed at many columns). I wanna get the biggest String at the "X" column and resize this colum.
Another problem consist of the Cells of JTable, in my AbstractModel class I wanna difene he type of the cells in the column. For example, I wanna that the 3th column will be a ComboBox, What I can do this!?!
Anyone can help me!?!? Thanks.

and I wanna made this using a one single command at the JAVA Swing API. Its possible, or I must resize each column at a time.There is no table method that will automatically resize each column to display the maximum string for the column.
Read this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables. This tutorial will show you how to display a combo box and how to set column widths.

Similar Messages

  • JTable resizing VS Horizontal scrollbar

    Heila',
    I have to show the content of a text file in a JTable; the JTable has 2 columns: the first contains the line number and the second column contains the text of the line.
    In order to allow the user to view and scroll the whole text line I added an horizontal scrollbar to the JTable.
    Here is the relevant code:
    gridVis.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    JPanGriglia = new JScrollPane(gridVis, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    JPanGriglia.getViewport().putClientProperty("EnableWindowBlit", Boolean.TRUE);     
    The problem is that if I set the AutoResizeMode to JTable.AUTO_RESIZE_OFF then I can see the horz scrollbar but when I resize the JFrame containing the JTable the JTable doesn't resize itself.
    Viceversa if I comment the statement:
    gridVis.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    then the JTable resizes correctly but the scrollbar disappears.
    Does exists the way to obtain both this features ?(correct resizing AND horizontal scroll bar)
    Thanks
    Ciao

    Try overriding getScrollableTracksViewportWidth() in JTable. The method returns a boolean value indicating whether the table should resize when its viewport is resized. If you setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS) and add a check to getScrollableTracksViewportWidth() such that it returns true only if viewport.getExtentSize().width is greater than some minimum width, then your table will resize automatically unless it is scaled below the minimum width, in which case a scrollbar will appear. If you're going to do this you'll need your JTable subclass to store a pointer to its scroll pane's viewport so it can get the extent size.

  • JTable - Resize rows the same way as the columns

    Hi!
    I have run into a very frustrating problem and have tried to solve this for many hours but can't come up with a good solution. If there is anyone that can help me on the right track I will be very grateful!
    When I'm using a JTable it provides good "graphical" functionality to handle resize of colums, but when it comes to resize rows it is not available.
    I have found a solution for the row height adjustment in the following post: [http://forums.sun.com/thread.jspa?forumID=257&threadID=453665]
    That solution only partially work in my case because of the following:
    The JTable exists inside a JInternalFrame and the JTable should not be able to get bigger then the actual size of the InternalFrame it is put in (so no scrollbar).
    The problem with the solution above is that the JTable total height will also expand when a row is resized (contrary to what happens when the columns are resized), ending up with a JTable that is bigger then the InternalFrame.
    So my question is:
    Is it possible to provide the same ("graphical") resize functionality for rows as for columns in a JTable? Or any row resize functionality that prevent the JTable from getting bigger then the container it is placed in?
    Thanks for your time!
    Best regards,
    Marcus

    Thanks for the fast answer!
    Yes, that would solve the height expanding problem. Thanks!
    It would be even better though if the row resize functionality would behave the same as the column resize (for consistency). For example: If a row is resized the other rows will get smaller so they all fit into the InternalFrame.
    It has to be some easy way to do this. I have started on a solution with component listeners etc. (to track resize) but it is quite hard to get it right and I keep getting the feeling I reinventing the wheel all over again:(
    Any ideas out there?

  • JTable resize header (and change mouse in between headings)

    Hi,
    I notice that i have the ability to resize my headings in the JTable but is there a way to get the mouse pointer to indicate something similar to what Excel does when you put your mouse over the divide (between two heading cells)?

    Here's my simple test program:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableTest2 extends JFrame
         public TableTest2()
              JTable table = new JTable(3, 3);
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableTest2 frame = new TableTest2();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • JTable resize of last column

    I've got a table with 2 columns, the tabel is inside a scroll pane. I want the first table column to be of fixed size and the second column to take up all of the viewports remaining width.
    I've setAutoResizeMode(JTable.AUTO_RESIZE_OFF) and getColumnModel().getColumn(0).setWidth(0), however, what method should I employ to determine resize, determine column 1's desired width based on the viewports width and set column 1's width?
    Thanks in advance,
    Jas

    The only thing I can think is that because there is no "NEXT COLUMN" to the one you are trying to resize it throws the ArrayIndexOutOfBoundsException. If you have 4 columns and you tell it to resize next column, and then you try to resize the right side of the 4 column it is trying to resize the next column, column 5, which does not exist and therefore throws the exception.

  • JTable: Resizable Row Header

    Hi,
    Did anyone implement a row header class for JTable that allows to resize rows (the height of rows) like JTableHeader does for columns?

    Take a look at the link shown below:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=252175
    ;o)
    V.V.

  • JTable:  resizing all columns as 1 column resizes

    I have a JTable with 480 columns inside of a JScrollPane (AUTO_RESIZE_ALL_COLUMNS needs to be off for the JTABLE to display correctly in the JScrollPane). When the user resizes one column I would like the rest of the columns to resize too, so that the column widths of each column are equal.
    Thank you in advance,
    Brent

    [...] I
    I have the JScrollPane listening to a histogram of the
    balances so the user can click on a month in the
    histogram and the JScrollPane (actually JViewport)
    will move to display the appropriate column in the
    JTable. If the column sizes are not uniform then I
    cannot be sure that I'm moving the JViewport to
    display the correct JTable column(s).
    I thing the GUI is a great design for what must be
    done. And thank you for your help and comments.That still sounds pretty klunky. I don't see any user navigating around a 480 column table. They click in your histogram to go to a column, they click somewhere or do keyboard navigation and the display scrolls them a few columns/rows away... they are now lost in a sea of cells and have to go back to the histogram again to try and get back, etc. Having delt with similar situations, there are better ways. Read the last two days dilbert cartoons carefully. :-)
    But anyway...
    You don't have to have all the columns the same width to make a column visible in the viewport. You can just get the appropriate column's rect by either of these methods:Rectangle r = myTable.getTableHeader().getHeaderRect( col );
    Rectangle r = myTable.getCellRect( row, col, true );And then tell the viewport to make sure that rect is visible:myViewport.scrollRectToVisible( r );Much easier than hacking around with custom column resizing logic.

  • Set JTable resize manual behaviour

    I've been trying for the better part of the day to implement a manual resize behavior for table column widths but without success.
    The JTable.setAutoResizeMode method that does this automatically has a couple of modes but not a weight mode (closest would be the one allocating new space equally to all columns, i.e. same weights).
    What I want to do is to change the columns width according to preset weights when the table changes size. The reason behind this is that I want to set the columns to a specific width percentage (e.g. 80% 10% 10% 0%). But when the application is resized and subsequently the table the percentages gets skewed since the AutoResizeMode (if set to ALL_COLUMNS) will add surplus space equally to all columns.
    My first approach was to implement a component listener that does just this:
    public void componentResized(ComponentEvent e) {
         JTable table = (JTable) e.getComponent();
         TableColumnModel model = table.getColumnModel();
         double before = 0.0d;
         for(int i = 0; i < model.getColumnCount(); ++i)
              before += model.getColumn(i).getWidth();
         double delta = table.getSize().getWidth() - before;
         for(int i = 0; i < model.getColumnCount(); ++i) {
              TableColumn column = model.getColumn(i);
              column.setWidth((int) (column.getWidth() + columnWeights*delta));
    ... but the AutoResizeMode overrides this but if I turn off the AutoResizeMode then the table will not resize at all which means the component listener wont do a thing.
    Any ideas as how to approach this problem would be appreciated!
    /Maigo                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Check out camickr's [Table Column Adjuster|http://tips4java.wordpress.com/2008/11/10/table-column-adjuster/]
    db

  • JTable resizing the column width

    Have a JTable whose column width's are set using
    int width = ((String)getDataTbl().getColumnModel().getColumn(0).getHeaderValue()).length() + 32;
    getDataTbl().getColumnModel().getColumn(0).setPreferredWidth(width);
    int width1 = ((String)getDataTbl().getColumnModel().getColumn(1).getHeaderValue()).length()+207
    getDataTbl().getColumnModel().getColumn(1).setPreferredWidth(width1);
    Now depending on the data in column 1 the column width has to be increased if more than width1 and the scroll bar should apprear only in this case only?
    How to do this?
    Thanks.

    maybe you can implement a interface ComponentListener as well as ComponentAdapter with your topmost Table.
    for example:
    toptable.addComponentListener(
    new ComponentAdapter(){
    public void componentResized(ComponentEvent e){
    table1.setSize(....);
    table2.setSize(....);
    /*Optionally, you must also call function revalidate
    anywhere;*/
    );

  • Resizing columns in a JTable in a JScrollpane

    I have a JTable in a JScrollpane and I after I load the table, I resize the columns to fit the data (works well).
    The problem is that I want the scrollpane to stay the same size and let the table scroll horizontally inside the viewport. The actual result is the scrollpane stretches to the width of the table causing the user to scroll the panel rather than the scrollpane.
    I've tried setting the scrollbar policy but that didn't work.

    I am passing the JTable to the constructor of the JScrollPane.
    I have a JTable in a JScrollPane that sits on a JPanel which is in a JScrollPane itself.
    After I load the data into the JTable, I resize all of the columns to fit the data.
    The problem is that the JTable resizes wider than original size causing the whole panel to scroll horizontally. I would rather have the JScrollPane that the JTable is in scroll.

  • How to make JTable use horizontal scrollbar

    My application uses a table to which data is added dynamically(both columns and rows). My problem is that when number of columns increase i want JTable to use horizontal scrollbar instead of resizing columns(which i achieve by setting resize mode to OFF state), But due to this if number of columns are less then there's alot of empty space left after showing columns(coz JTable cannot resize cols to fit Viewport area). To achieve both criteria i used following solution
    1. Set Auto resizing to OFF.
    2. Check if width of table is less than viewport width and if so then set auto
    auto resizing ON :) which will fit columns in viewport thereby occupying empty space.
    But this solution doesn't seem to be straight and simple to me. Is anyone aware of a simple solution to this problem.
    Dimension dm_Dm = new Dimension();
        RSBrowser.setModal(false);
        browseTable_Jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        // reqd o.w. JTable resizes column widths instead  of using horizontal
        // scrollbar
        RSBrowser.setVisible(true);
        browseTable_Jt.getSize(dm_Dm);
        // if table width is less than total viewport size then fill the extra
        // space by setting suto resize property to ON.
        if ( browseTable_Jt.getPreferredScrollableViewportSize().getWidth() >
             dm_Dm.getWidth() )
            browseTable_Jt.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
            browseTable_Jt.doLayout();
        RSBrowser.setModal(true);

    hi,
    with your problem statement it seems you should use javax.swing.JScrollPane like the one below
    JScrollPane tableScroller = new JScrollPane(yourTable);
    tableScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    tableScroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);hope this helps you,
    regards,
    Afroze.

  • Resize JTable in JTabbedPane

    Given the FileTableDemo from the Java Foundation Class in a Nutshell book.(O'Reilly) Chapter 3 page 51 in my addition.
    I have modified the example to place the JTable in a JTabbedPane. Now when the window (JFrame) is resized by the user the JTable no longer resizes. How do I passing the "resizing" into the component (JTable) placed in the JTabbedPane?
    Here is the code: My deviation from the example is enclosed in "///////////KBS" and of course the line frame.getContentPane().add(myTP, "Center"); where "pane" has been replaced with "myTP"
    Thanks Brad
    import javax.swing.*;
    import javax.swing.table.*;
    import java.io.File;
    import java.util.Date;
    public class FileTableDemo
    public static void main(String[] args)
    // Figure out what directory to display
    File dir;
    if (args.length > 0)
    dir = new File(args[0]);
    else
    dir = new File(System.getProperty("user.home"));
    // Create a TableModel object to represent the contents of the directory
    FileTableModel model = new FileTableModel(dir);
    // Create a JTable and tell it to display our model
    JTable table = new JTable(model);
    JScrollPane pane = new JScrollPane(table);
    pane.setBorder(BorderFactory.createEmptyBorder(60,20,20,20));
    ////////KBS
    JTabbedPane myTP = new JTabbedPane();
    JPanel myOne = new JPanel();
    JPanel myTwo = new JPanel();
    myOne.add(pane);
    myTP.add("One", myOne);
    myTP.add("Two", myTwo);
    ////////KBS
    // Display it all in a scrolling window and make the window appear
    JFrame frame = new JFrame("FileTableDemo");
    frame.getContentPane().add(myTP, "Center");
    frame.setSize(600, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    // The methods in this class allow the JTable component to get
    // and display data about the files in a specified directory.
    // It represents a table with six columns: filename, size, modification date,
    // plus three columns for flags: direcotry, readable, writable
    class FileTableModel extends AbstractTableModel
    protected File dir;
    protected String[] filenames;
    protected String[] columnNames = new String[] {
    "name",
    "size",
    "last modified",
    "directory?",
    "readable?",
    "writable?"
    protected Class[] columnClasses = new Class[] {
    String.class,
    Long.class,
    Date.class,
    Boolean.class,
    Boolean.class,
    Boolean.class
    // This table model works for any one given directory
    public FileTableModel(File dir)
    this.dir = dir;
    this.filenames = dir.list();
    // These are easy methods
    public int getColumnCount()
    return 6;
    public int getRowCount()
    return filenames.length;
    // Information about each column
    public String getColumnName(int col)
    return columnNames[col];
    public Class getColumnClass(int col)
    return columnClasses[col];
    // The method that must actually return the value of each cell
    public Object getValueAt(int row, int col)
    File f = new File(dir, filenames[row]);
    switch(col)
    case 0: return filenames[row];
    case 1: return new Long(f.length());
    case 2: return new Date(f.lastModified());
    case 3: return f.isDirectory() ? Boolean.TRUE : Boolean.FALSE;
    case 4: return f.canRead() ? Boolean.TRUE : Boolean.FALSE;
    case 5: return f.canWrite() ? Boolean.TRUE : Boolean.FALSE;
    default: return null;
    }

    Well, I didn't find an answer but I did find a solution.
    The JPanel is the problem. I use it to help with layout which is not obvious in this example.
    As you can see in the code the JTable is placed in a JScrollPane which is place in a JPanel which is placed in a JTabbedPane.
    If I use Box instead of JPanel the JTable in the JScrollPane in the Box in the TabbedPane in the JFrame resizes correclty.
    So although JPanel is resizable with setSize it does not get resized when it's JFrame gets resized.
    I would still like to know why?
    ////////KBS
    JTabbedPane myTP = new JTabbedPane();
    Box myOne = Box.createHorizontalBox();
    Box myTwo = Box.createHorizontalBox();
    myOne.add(pane);
    myTP.add("One", myOne);
    myTP.add("Two", myTwo);
    ////////KBS

  • Resize cells in a JTable.

    I'd like to give some columns, in a jTable, an autoresize mode. It means fitting well with the content (being able to read the longest cell without having to resize the cell manualy by resizing the header).
    Some tables of other applications (like the Excel ones) hava this ability.
    Do S.O. have any idea of doing this?
    Thanks.

    extend a new class from javax.swing.table.DefaultTableCellRenderer
    and use setCellRenderer(...) on your JTable

  • Resize Row in a JTable??

    Hi,
    Is it possible to allow the 'user' to resize the height of a row in JTable??
    I know that we can programatically set the height of a row through setRowHeight method.
    But my requirement is to allow the 'user' to resize the height of a row. If resized, how can I get the new height of the row??
    Regards,
    Satish

    Very interesting and difficult question.
    I think the best way is to create a row header (like in excel) which allows to resize the rows individually.
    I will work on this problem.
    Denis

  • JTable in JPanel last Column resize clips JTable doesnt repaint JPanel

    I have a JTable in a JPanel, when I drag the last column of the JTableHeader (u can see the column resizing as the text of the Table HeaderColumn moves with the drag) the JTable is outside the JPanel. Only when u click on another component and then click back on the JTableHeader does it repaint.
    I have tried jPanel.revalidate(); in the mouseDragged event of MouseMotionListener on the JTableHeader and all manner or repaints and fireTableStructureChanged. But I dont understand the order of events.
    The last bug to fix!!!
    NB I dont want to use scrollpane as its not necessary and as many tables are synchronized with one table it makes repaints less smooth
    Thanks Paul

    Well, I didn't find an answer but I did find a solution.
    The JPanel is the problem. I use it to help with layout which is not obvious in this example.
    As you can see in the code the JTable is placed in a JScrollPane which is place in a JPanel which is placed in a JTabbedPane.
    If I use Box instead of JPanel the JTable in the JScrollPane in the Box in the TabbedPane in the JFrame resizes correclty.
    So although JPanel is resizable with setSize it does not get resized when it's JFrame gets resized.
    I would still like to know why?
    ////////KBS
    JTabbedPane myTP = new JTabbedPane();
    Box myOne = Box.createHorizontalBox();
    Box myTwo = Box.createHorizontalBox();
    myOne.add(pane);
    myTP.add("One", myOne);
    myTP.add("Two", myTwo);
    ////////KBS

Maybe you are looking for