Saher Ahwal Saher Ahwal - 1 year ago 108
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);

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

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).?


Answer Source

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() {

            public void run() {
                JFrame f = new JFrame();

                // 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

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