Saher Ahwal Saher Ahwal - 3 months ago 22
Java Question

JTable set column size problem

I am having this problem of setting column width of JTable.

The code below works fine:

TableColumn a =shipsAndOwnHitsTable.getColumnModel().getColumn(0);
a.setPreferredWidth(800);


It changes the width of the first column.

However when placed in a while or a for loop, nothing happens:

int index = 0;
while (index < columnNum){
TableColumn a =shipsAndOwnHitsTable.getColumnModel().getColumn(index);
a.setPreferredWidth(800);
index+=1;
}


This code doesn't work, nothing happens to the column sizes, can someone explain why?
If not can someone tell me how to set the row and column width to be the same, i.e I want all cells in my table to be square, regardless of table size(rows and columns).?

Thanks

Answer

The following code works fine. According to my comments, note that

  • setAutoResizeMode(JTable.AUTO_RESIZE_OFF) was called
  • the table component is embedded into a JScrollPane to allow arbitrary size

Compare it with your code and you might spot your issue quite soon.

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;

public class TableColumnSizeTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                // prepare table
                JTable table = new JTable(new String[][] {  
                                 { "Row 1 Col A", "Row 1 Col B" }, 
                                 { "Row 2 Col A", "Row 2 Col B" } }, 
                                 new String[] { "ColA", "ColB" });

                // add into scroll pane
                f.getContentPane().add(new JScrollPane(table));

                // turn off auto resize
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

                // set preferred column widths
                int index = 0;
                while (index < 2) {
                    TableColumn a = table.getColumnModel().getColumn(index);
                    a.setPreferredWidth(10);
                    index++;
                }

                f.pack();

                f.setVisible(true);
            }
        });
    }
}
Comments