Help with JTable column width

Hi,
I'm trying to resize my JTable columns with this code, but it's not working. What I am doing wrong?
for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
TableColumn tc = table.getColumnModel().getColumn(i);
int width = (i == 0)? 10 : table.getWidth()/2 - 10; // three columns
tc.setPreferredWidth(width);
Thanks,
Andr�

Now my problem is that using either of these methods
is they don't carry the user's selected column width
through updates.It sounds like the change event your table model is firing is causing the entire table to be rebuilt. I would guess that you are firing fireTableStructureChanged() which would cause the entire table to be rebuilt (columns, cell values, etc.) Just fire a change event for the minimum necessary. If you can't identify what data in your table has changed (to fire cell or row change events), but the structure (columns) of the table hasn't changed, just fire fireTableDataChanged(). This will cause the cells to be redrawn with the new values, but shouldn't cause the columns to be rebuilt and resized.

Similar Messages

  • Proglem with JTable column width

    Hi Friends,
    I'm using jtable. For that table, i want to set the column width. But it is not working. Here is my code...
    class ProcessTable extends JTable {
    ProcessTable(){
    getTableHeader().setResizingAllowed(true);
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         TableColumn col = getColumnModel().getColumn(0);
         col.setPreferredWidth(100);
         col = getColumnModel().getColumn(1);
         col.setPreferredWidth(130);
    }

    Either don't change the TableModel or make sure you don't call fireTableStructureChanged() but fireTableDataChanged() (meaning loading the data doesn't change the columns, just the rows).
    Or you can use JTable.setAutoCreateColumnsfromModel(false) and create the TableColumnModel yourself.

  • JTable column widths - help

    Hi,
    I have a JTable and I am having problems with the column widths. Currently, I place my JTable in a JScrollPane, and that's it. What I want is this:
    1. When the table is initially displayed, I want all the columns to be of equal width and use the entire width of the table (so no empty space at the end of the table)
    2. When I resize a column I want the other columns to maintain their size, and just have the scroll bars appear.
    3. When I resize the frame/browser that my app is running in, I want the scroll bars to appear.
    I tried the different autoResizeModes but I cant get the entire result which I need..any suggestions? Below is a code example...
    import java.awt.BorderLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class Test1 extends JPanel {
         JScrollPane scroller;
         JTable table;
         String[][] rowData = new String[][] {
                   {"John", "18"},
                   {"Bill", "20"},
                   {"Alex", "17"}
         String[] columns = new String[] {
              "Name", "Age"     
         public Test1() {
              table = new JTable(rowData, columns);
              scroller = new JScrollPane(table);
              setLayout(new BorderLayout());
              add(scroller, BorderLayout.CENTER);
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Test1 t = new Test1();
              f.getContentPane().add(t);
              f.setSize(600, 600);
              f.setVisible(true);
    }

    Forget about my last post. The following code works but I guess you'll have to work on it to make it more elegant.import java.awt.BorderLayout;
    import javax.swing.*;
    public class Test1 extends JPanel {
         String[][] rowData = new String[][]{{"John", "18"}, {"Bill", "20"}, {"Alex", "17"}};
         String[] columns = new String[]{"Name", "Age"};
         JTable table;
         JScrollPane scrollPane;
         public Test1() {
              super(new BorderLayout());
              table = new JTable(rowData, columns);
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              scrollPane = new JScrollPane(table);
              add(scrollPane, BorderLayout.CENTER);
         public void pack() {
              System.out.println("pack");
              int columnCount = table.getColumnCount();
              if (columnCount == 0) {
                   System.out.println("columnCount = 0");
                   return;
              int width = scrollPane.getViewport().getSize().width;
              System.out.println("width = " + width);
              if (width == 0) return;
              int columnWidth = width / columnCount;
              System.out.println("columnWidth = " + columnWidth);
              for (int i = 0; i < columnCount; i++) {
                   table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth);
              table.revalidate();
              table.repaint();
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final Test1 t = new Test1();
              f.setContentPane(t);
              f.setSize(600, 600);
              f.setVisible(true);
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        t.pack();
    }

  • What method should be used for resizing the particular JTable Column width

    I have a four table. Only one table which are on top have a table header. I want that when user resize the topmost table with a mouse other table colume also be resized automatically. So I want to know that what method should be used for resizing the particular JTable Column width.
    Thanks
    Lalit

    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;*/
    );

  • How to size JTable Column width?? Need help

    Using the following logic to size column width, but only the 1st column is sized. How can I get the other columns sized??
    int widthsSummary[] = {340,60,150,60,60};
    for (int i=0; i<1; i++)
    column = getScrollPaneTableSummary).getColumnModel ().getColumn(i);
    column.setMinWidth(widthsSummary);
    column.setMaxWidth(widthsSummary[i]+50);
    column.setPreferredWidth(widthsSummary[i]);          

    First, take a look at your for loop
    for (int i=0; i<1; i++)i starts at 0 and cannot be equal to or greater than 1. This loop will only occur once, when i = 0.
    Second, take a look at your set...Width calls
    column.setMinWidth(widthsSummary);
    column.setMaxWidth(widthsSummary+50);
    column.setPreferredWidth(widthsSummary); widthsSummary is an array. You need a number to set widths. Try ...set...width(widthsSummary);
    Hope that helps.

  • Is there a jtable column width minimum?

    Hi,
    I try to set the column width in a JTable to 3 or 5, but it seems that there is a hard minimum width of 15.
    I use
    table.getColumnModel().getColumn(0).setMaxWidth(3);
    Just afterwards I get with
    System.out.println("width: "+table.getColumnModel().getColumn(0).getWidth());
    width: 15
    I tried to set autoresize false, validate, repaint, .... Nothing helps. I have no table header. It doesn't matter if I use a custom cell renderer or the default. If I set the width to e.g. 30, it works. But no way to get below 15.
    Thanks, Ulrich

    >
    table.getColumnModel().getColumn(0).setMaxWidth(3);
    Try this instead
    table.getColumnModel().getColumn(0).setPreferredW
    dth(3);ICE
    The default minimum is 15, there is a setMinWidth function.
    table.getColumnModel().getColumn(0).setMinWidth(3);then I would try setting the preferred width.

  • Set JTable column width

    Hi,
    I would like to set the column width of JTable.
    ========================================
    JTable table;
    DefaultTableModel tableModel;
    tableModel = new DefaultTableModel();
    table = new JTable( tableModel);
    JScrollPane scrollPane = new JScrollPane(table);
    for(int i = 0; i < heading.length; i++)
    tableModel.addColumn( heading[ i ]);
    ========================================

    Did you run the tutorial code? Did it work?
    Now compare the tutorial code with your code to determine what is different.
    We can't tell you what is different based on the one line of code you posted:
    colModel.getColumn(i).setPreferredWidth(100);

  • Setting exact    jtable column width

    I need to set each column width in table 200. Columns are added dynamically. And after one column added the previous one width is become small(about 75).
    There is test code. Please, help, here is last place I can find the answer.
    package visual.jtable;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import java.awt.*;
    import java.io.File;
    import java.util.Arrays;
    import java.util.List;
    import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
    public class TestFrame extends JFrame
        public JTable table;
        public TestFrame()
            super("Test frame");
            createGUI();
        public void createGUI()
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            table = new JTable();
            table.setBounds(400, 400, 700, 300);
            JScrollPane pane = new JScrollPane(table);
            System.out.println(pane.getLayout().getClass().toString());
            pane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            pane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            panel.add(pane, BorderLayout.CENTER);
            getContentPane().add(panel);
        static int lastCol = -1;
        static int lastRow = -1;
        static int visibleRows = 13;
        public static void addFile(JTable table, File file)
            DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
            if (lastRow == visibleRows - 1 || lastCol == -1)
                TableColumnModel cm = table.getColumnModel();
                table.getTableHeader().setResizingAllowed(false);
                table.setAutoscrolls(true);
                table.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
                tableModel.addColumn(String.valueOf(lastCol + 1), new File[visibleRows]);
                int index = tableModel.findColumn(String.valueOf(lastCol + 1));
                cm.getColumn(index).setMinWidth(200);
                cm.getColumn(index).setMaxWidth(200);
                cm.getColumn(index).setWidth(200);
                cm.getColumn(index).setPreferredWidth(200);
                cm.getColumn(index).setResizable(false);
                System.out.println("width = " + cm.getColumn(index).getWidth());
                System.out.println(table.getAutoResizeMode());
                lastCol++;
                lastRow = -1;
            lastRow++;
            tableModel.setValueAt(file, lastRow, lastCol);
        public static void main(String[] args) throws Exception
            JFrame.setDefaultLookAndFeelDecorated(true);
            try
                UIManager.setLookAndFeel(new WindowsLookAndFeel());
            catch (Exception e)
            TestFrame frame = new TestFrame();
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            List<File> f = Arrays.asList(FileSystemView.getFileSystemView().getFiles(new File("C:\\Documents and Settings\\Admin\\&#1056;&#1072;&#1073;&#1086;&#1095;&#1080;&#1081; &#1089;&#1090;&#1086;&#1083;"), false));
            for (File file : f)
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
    class ListViewTableCellRenderer2 extends DefaultTableCellRenderer
       // public ListViewTableCellRenderer(){}
        // implements javax.swing.table.TableCellRenderer
        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
            Component component = super.getTableCellRendererComponent(
                    table, value, isSelected, hasFocus, row, column);
            File file = (File) value;
            JLabel label = (JLabel) component;
            label.setMinimumSize(new Dimension(200, label.getHeight()));
            label.setMaximumSize(new Dimension(200, label.getHeight()));
            label.setPreferredSize(new Dimension(200, label.getHeight()));
            label.setSize(200, label.getHeight());
            label.setMinimumSize(new Dimension(200, label.getHeight()));
            label.setText("<table width=\"200\">" +
                    "  <tr>" +
                    "    <td>Month</td>" +
                    "  </tr>" +
                    "</table>");
            if(file == null)
                label.setIcon(null);
                return label;
            //label.setIcon(ViewManager.getCachedIcon(file));
              label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(file));
            if(file.isHidden())
               label.setText("<html><font color = \"red\">" + file.getName() + "</font></html>");
            label.setText(file.getName());
            label.setText("<table width=\"200\">" +
                    "  <tr>" +
                    "    <td>Month</th>" +
                    "  </tr>" +
                    "</table>");
            return label;
    }

    And after one column added the previous one width is become small(about 75).The model.addColumn() method causes a fireTableStructureChanged event to be generated which causes the TableColumns to be recreated and therefore they default back to their default sizes.
    So you need to prevent the columns from being recreated. You do this by adding:
    JTable table = new JTable(....);
    table.setAutoCreateColumnsFromModel(false);But now you are responsible for adding table columns to the table manually. So your code would be something like;
    int index = model.getColumnCount();
    model.addColumn(...);
    TableColumn tc = new TableColumn(index);
    tc.setHeaderValue("" + index);
    table.addColumn( tc );

  • JTable  Column Width Settings ??

    Hello!
    Using netbeans IDE 3.6 , I created a jTable with 12 columns with the form builder ...
    ... Question : I want to set the widths (all of which are different) of the columns when the Table loads.
    .... can this be done in Preferences API ?
    Thanks!

    ... Thanks!
    .... but i just now see how its done ...
    AddRFSwitchMain.jTable1.getColumnModel().getColumn(1).setPreferredWidth(100);

  • RH 10 issue with Fixed Column width

    Hi,
    Is anybody else having issues with setting a fix width for a column in a table?  In RH v.10 the "fixed widths" are not staying "fixed" as I have them manually set.
    I've recently been upgraded from Robohelp (html) v.8 to v.10. 
    In a "Design" view in v.8.0 when I set a column width from the right click menu (AutoFit > Fixed Column Width), the width of the column would be whatever width I'd set it to.  Now, in v.10, the width is whatever width the Robohelp window is set to!  For example, I have a large monitor and I've got Robohelp open in Full Screen mode, the table (a 1-cell table) gets set to the width of the window rather than the particular width I want to use!  I want the cell to be a particular width (much less than my monitor or the open window's width).  Can someone please tell me what I am doing wrong?
    OS=Windows7.
    Browser=IE9
    Robohelp is installed locally (it is not being run over a network).
    Thanks!
    P.S. So far this is the only issue I've had after upgrading from RH v.8 to RH v.10.

    Hi William,
    In a "Design" view in v.10, the table (which is 1 cell) looks like a big rectangular box.  I've turned off the border (cell or table border), so the border appears in gray. 
    Put mouse focus on this 1-cell table, then grab an edge with the mouse. 
    Move the table inward to make the column narrower in the view.
    Then from the right click menu, choose AutoFit > Fixed Column Width.
    Voilá - the width is back to the width of the display window.
    Did that make sense to you?   Thank you for your help and ideas.
    Cheers,
    Julia

  • Tweaking JTable column widths

    One of the things I don't seem to be able to do cleanly is programatically sizing column widths. What I'm trying to do, presently, is to try and set column widths on numeric columns according to class.
    This is what I'm trying:
       public static void tweakColumns(JTable table) {
            TableColumnModel tcm = table.getColumnModel();
            TableModel data = table.getModel();
            table.createDefaultColumnsFromModel();
            for(int i = 0; i < tcm.getColumnCount(); i++) {
                TableColumn col = tcm.getColumn(i);
                Class cls = data.getColumnClass(i);
                if(cls.equals(Percentage.class))
                    col.setPreferredWidth(44);
                else if(cls.equals(Money.class))
                    col.setPreferredWidth(60);
                else if(cls.equals(Integer.class))
                    col.setPreferredWidth(20);
            table.revalidate();
        }I've tried calling this when I set the table up, I've tried defering it with invokeLater. The problem appears to be when there's plenty of space the additional space is applied indiscrimitely, smothering my settings, whereas I want the extra to be applied to the columns I don't set preferences for (typically text fields).
    I don't want to impose a maximum column width if the user choses to resize columns. I want to control the distribution of space when it's done by swing.

    I think your only solution is to set the Preferred sizes of all the columns, even the textfields.
    I have done similar thing and it works but only when all the preferred sizes of all the columns are set.
    If you record the total width available to all columns before you start setting the preferred sizes of the Percentage, Money and Integer columns you can subtract the sizes of these columns as you set them. When you come out of the loop you will have a value that is what is left of the width. You can then set all the remaining unset columns to values based on this remaining width.
    i.e. you have 700 pixels total width the the initial loop you have fields that result in 340 pixels being allocated. You have 360 pixels left over. If you have 3 remaining unset fields then you then set their preferred sizes to be 120 pixels. This, I think, will force swing to allocate in the way you want.
    I've never tried it but you might find setting the textfields to unrealistically large Preferred sizes will make swing attempt to do its best and end up with what you want.

  • Help with XHTML columns in IE6

    I'm having some problems with my columns in IE6. The math is
    all correct and it lays out perfectly fine in firefox as expected.
    For some reason IE6 seems to be doubling the numbers I assign as my
    margins. Can anyone give me a tip as to what's wrong here before I
    trash this whole idea and go with a old fashioned table.
    2 columns.
    15px left and right margins on the "left" column, 470px wide
    15px right margin on the "right"column, 455px wide

    Its an IE6 float/margin bug. If you add a margin in the same
    direction
    as the float IE6 will double it. Add display: inline; to the
    css styles,
    as below, to counter-act this problem.
    #left { margin: 0 15px; width: 470px; height: 100px; float:
    left;
    background: #f00; display: inline; }
    #right { margin: 0 15px 0 0; width: 455px; height: 100px;
    float: right;
    background: #666; display: inline; }
    quovadimus02 wrote:
    > I'm having some problems with my columns in IE6. The
    math is all correct and
    > it lays out perfectly fine in firefox as expected. For
    some reason IE6 seems
    > to be doubling the numbers I assign as my margins. Can
    anyone give me a tip as
    > to what's wrong here before I trash this whole idea and
    go with a old fashioned
    > table.
    >
    > 2 columns.
    > 15px left and right margins on the "left" column, 470px
    wide
    > 15px right margin on the "right"column, 455px wide
    >
    >
    >
    > <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Transitional//EN"
    > "
    http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    > <html xmlns="
    http://www.w3.org/1999/xhtml">
    > <head>
    > <meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1" />
    > <title>Untitled Document</title>
    > <style type="text/css">
    > body { margin: 0; padding: 0; width: 970px; background:
    #e1e1e1; }
    > #wrap { padding: 10px 0; background: #fff; }
    > #left { margin: 0 15px; width: 470px; height: 100px;
    float: left; background:
    > #f00; }
    > #right { margin: 0 15px 0 0; width: 455px; height:
    100px; float: right;
    > background: #666; }
    > </style>
    > </head>
    > <body>
    > <div id="wrap">
    > <div id="right"></div>
    > <div id="left"></div>
    > <div style="clear: both;"></div>
    > </div>
    > </body>
    > </html>
    >

  • Spark DataGrid with Dynamic Column Width

    Lets suppose I have a Spark Datagrid with no explicit typicalItem. When the Datagrid is initialized, the column widths are calcualted correctly based on the contents of the dataprovider. However if I add/remove an item from the dataprovider, or modify the one of the objects in the dataprovider, the column widths never update to reflect the change. Is the the correct behavior for a DataGrid? If so, is there any method I can call to force the DataGrid to recalculate and redraw the column widths?

    When Spark DataGrid doesn't have a typicalItem, it uses the first dataProvider item as the typicalItem.  If you change that, the DataGrid won't pick it up immediately. You can invalidate the current typicalItem using dataGrid.invalidateTypicalItem().

  • How to set jtable column width

    Hello..
    I 'm using a simple jtable with the default model. I just want to set each column size to make table smaller Is this possible?
    Thanks
    Feras

    newdeveloper wrote:
    Hello..
    I 'm using a simple jtable with the default model. I just want to set each column size to make table smaller Is this possible?
    Thanks
    FerasI think that your problem probably has more to do with the Layout you're using (or not using) than it does with individual column sizes. What layout are you using?
    What happens when you set the size (or preferredSize, minimumSize, and maximumSize) on the whole JTable?
    You might also be looking for JTable.[getColumnModel()|http://download-llnw.oracle.com/javase/6/docs/api/javax/swing/JTable.html#getColumnModel%28%29].[getColumn()|http://download-llnw.oracle.com/javase/6/docs/api/javax/swing/table/TableColumnModel.html#getColumn%28int%29].[setPreferredWidth()|http://download-llnw.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setPreferredWidth%28int%29].
    If none of those approaches work, post an SSCCE that demonstrates the problem.
    PS- Swing questions belong in the Swing forum.

  • Setting the jTable column width

    Coming from VB6 to Java is hard for me. Syntax is so much different.
    Below is what I am doing to populate the jTable and the values are coming from MySQL. My problem is setting the column width but I am having difficult understanding how to do it. I looked on the website and downloaded some examples and clearly because I am new and I simply do not understand it. I was wonder if someone is willing to modify the codes below on how I should do it. Thanks
    private void populate_grid(){
    Vector dataVector = new Vector();
    Vector columnVector = new Vector();
    columnVector.add("ID#");
    columnVector.add("Account Description");
    columnVector.add("Contact");
    columnVector.add("State");
    while (myResult.next()) {
    Vector rowVector = new Vector();
    System.out.println(myResult.getString("acct_name"));
    rowVector.add(myResult.getString("cust_id"));
    rowVector.add(myResult.getString("acct_name"));
    rowVector.add(myResult.getString("main_contact"));
    rowVector.add(myResult.getString("main_state"));
    dataVector.add(rowVector);
    jTable1.setModel(new javax.swing.table.DefaultTableModel(dataVector, columnVector));

        int rows = 3;
        int cols = 3;
        JTable table = new JTable(rows, cols);
        // Disable auto resizing
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        // Set the first visible column to 100 pixels wide
        int vColIndex = 0;
        TableColumn col = table.getColumnModel().getColumn(vColIndex);
        int width = 100;
        col.setPreferredWidth(width);

Maybe you are looking for

  • Connecting iPads to an Enterprise Wireless 802.1x (EAP-TLS) Network Using Windows Server 2003 IAS

    Hi there, I am asked to deploy iPads on an 802.1x EAP-TLS WiFi network. The customer has a Windows Server 2003 IAS server providing RADIUS. There also is a Windows based CA infrastructure in place. This solution is in production and is already being

  • Unable to Install QTP 10 - in Windows 7 - 64 Bit - Home Premium

    Hi Team, While am trying to install QTP 10 in Windows 7, 64 bit Machine an issue is observed, "This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that

  • Preview fails to open a file that Adobe Reader will open

    I get statements from Wells Fargo downloaded with filenames like session5.cgi. If I double click them, they open just fine in Adobe Reader. But if I control-click and specify Preview as the application, then nothing happens and the fie is not opened.

  • OVKK--Condition Type?

    Hello All, When you define the determination of pricing procedure in txn OVKK, there is a field 'Condition Type'. What is this used for..? The F1 says: Proposed condition type for fast entry     The condition type that the system automatically propos

  • Help required to get data from Cash Mgt

    Hi I need help to get following data from cash managemment . Bank Name Branch Account# Date cheque#/Ref Amount Direct Debited by bank Amount Direct credeted by bank. Kindly help Regards