Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable set column size problem

Tags:

java

swing

jtable

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

like image 646
Saher Ahwal Avatar asked Apr 25 '11 05:04

Saher Ahwal


1 Answers

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);
            }
        });
    }
}
like image 109
Howard Avatar answered Oct 09 '22 06:10

Howard