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();
}

Similar Messages

  • 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.

  • 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.

  • 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.

  • 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 );

  • 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 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);

  • 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 width

    I am having trouble initializing column widths in my JTable.... after I create the table I use JColumn.setWidth(int) to set the width of every column. It doesn't work! the table sets
    default equal widths. Am trying like this :
         if(e.getSource()==column)
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);     
    for(int i=0;i<table.getColumnCount();i++)
    table.getColumnModel().getColumn(i).setPreferredWidth(Integer.parseInt(column.getText()));
    modelTable.fireTableStructureChanged();     
         }

    Instead of setPreferredWidth(..), try setMaxWidth(..)
    table.getColumnModel().getColumn(i).setMaxWidth(Integer.parseInt(column.getText()));
    I does the trick for me.

  • Fitting JTable column widths

    Hi,
    I have a JTable that it's columns are in AUTO_RESIZE_OFF mode. The table is in a JScrollPane that it's scrolls are shown when needed. The problem is that the table columns don't fill the scroll pane (horizontally) and because I'm using a layout I don't know that scroll size until the component appears. I need to set the column widths before the table appears.
    Is there a solution for this problem?
    Thanks,
    Shai

    To fill all the scrollpane you must use AUTO_RESIZE_ALL_COLUMNS or another mode different from AUTO_RESIZE_OFF. But in this case, rhe horizontal scrollbar won't appear.
    I found a workaround to show the scrollbar when the viewport width is smaller than the preferred width of the JTable.
    Denis

  • 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.

  • Adjust JTable column width according to content

    'morning all,
    How can I resize each column's width according with the content ? I mean, i'd like to show all the content of my cells, neither clipped nor with leading space.
    Can something help me, please ?
    Bye bye by Dhavide - we will, forever -

    If you don't set specific font for individual cells, your JTable inherited a default font from the Component class. You can try something like this (untested):
    FontMetrics FM=getFontMetrics(myTable.getFont());
    int j=0;
    int col=1;  // or whatever column you want to change width
    String out;
    for (int row=0;row<maxRow;row++) {
       out=myTable.getValueAt(row,col);
       if (FM.stringWidth(out)>j) j=FM.stringWidth(out);
    myTable.setColWidth(col,col+1,j);          // width plus a fudge factorwhere myTable is a reference to your own table and out is the label in each row in the column that you want to change the width.
    ;o)
    V.V.

  • Resize jtable column width

    I am trying implement a utility in JTable by which when a person clicks on the column header, the whole column should resize according to the cell which has lengthiest data. If you have seen this in MS Excel where by clicking on the column this happens. I want the same thing.
    Is there anyway already defined in javax.swing?
    I have added a Mouselistener on Tableheader and when the person clicks on a column header, I first finds out the column index. Now on that column index scan the whole column for the lengthiest data. After finding the lengthiest data I set the preferred width for that column and call doLayout on the table object. In this case the problem is of font as the font is not fixed width. The multiplication factor which returns the pixel doesn't gives the right pixel width. Is there any way by which I can find pixel width of a String?

    Use the following code to compute the width of a
    column in pixels required to display the maximum sized
    string in the table column:
    FontMetrics fm =
    table.getFontMetrics(table.getFont());
    int width =
    SwingUtilities.computeStringWidth(fm,maxSizeString)
    //then to set the width of your column:
    TableColumnModel columnModel =
    table.getColumnModel();
    TableColumn column =
    columnModel.getColumn(YOUR_COLUMN);
    column.setPreferredWidth(width);Rizwanthx that was usefull

  • Adjusting JTable column width

    I want to set the width of one column and let the other columns have the rest of the width in the table. Right now I am doing this by setting the width of each column. But can someone please tell me if it is possible to do programmatically.
    I have tried to use sizeWidthToFit(). But it does not work. I have also set the headers to null.
    Thanks,
    sjl

    hi Mark,
    you can try C_CELL_TD_EXTEND
    e.g C_CELL_TD_EXTEND = 'width=200'.
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/b1089290-0201-0010-288c-98e4d26487ee
    Extension of TD tag
    Here you can set the properties such as the width, height, alignment or color of the cell. This parameter is not normally set because many of the properties are already defined when the style is defined.
    hope this helps.

Maybe you are looking for

  • Lion Internet Recovery does not work

    Lion Internet recovery appears to be broken... On my 27" i5 QC 2010 iMac when to receover via Internet I am unable to do so  I tried it using wired networking first and then wireless, same lack of results on both. I succesfully identify myself with m

  • Flash Player unexpectedly quitting

    I've been racking my brains on this for weeks with no solution, so I hope someone here can help. I have a browser-based SWF application that I created in Flex 3. This is a digital signage application that runs almost 24/7 that displays data on a moni

  • Cost Analysis

    Hi Guru's, I am facing problem  with Production Order Analysis against with the Sales Order. Sales Order Number : 400001 Production Order : 400000130 This  Order created on April. We run Standard Cost on 22nd June,2011. The material  Master price is

  • ThinkVantage after New XP install?

    I recently purchased a used T60 2007-CTO (off-corporate lease). The harddrive was wiped and only XP was reinstalled. It seems that the primary drivers were reinstalled, as there is no problem with the wireless networking, but the ThinkVantage button

  • List of Countries in SAP

    Hi, I am using the SAPJCO and wish to get a list of country codes from SAP and their text representation.  For example when I extract data from an info type the country is represented as an integer, I wish to translate these to real country names, ca