tags:

views:

104

answers:

2

For the following code, I am not able to set the column size to a custom size. Why is it so?Also the first column is not being displayed.

    import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

public class Trial extends JFrame{
   public void create(){
     JPanel jp = new JPanel();
     String[] string = {" ", "A"};
     Object[][] data = {{"A", "0"},{"B", "3"},{"C","5"},{"D","-"}};
     JTable table = new JTable(data, string);     
     jp.setLayout(new GridLayout(2,0));   
     jp.add(table);

     table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
     TableColumn column = null;
     for (int i = 0; i < 2; i++) {
        column = table.getColumnModel().getColumn(i);
        column.setPreferredWidth(20);      //custom size
       }
     setLayout(new BorderLayout());
     add(jp);
   }

   public static void main(String [] a){
      Trial trial = new Trial();
      trial.setSize(300,300);
      trial.setVisible(true);
      trial.setDefaultCloseOperation(Trial.EXIT_ON_CLOSE);
      trial.create();
   }
}
+3  A: 

You've got a couple of issues here. First and foremost, Always initialize your JFrame from the Swing EDT as such:

   public static void main(String[] a) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            Trial trial = new Trial();
            trial.setSize(300, 300);
            trial.setDefaultCloseOperation(Trial.EXIT_ON_CLOSE);
            trial.create();
         }
      });
   }

Failure to do so will lead to subtle errors. Second: JTables like to exist within JScrollPanes. That's why you don't see the column headers:

  JScrollPane pane = new JScrollPane();
  pane.setViewportView(table);
  jp.add(pane);

With the above done, I see your tiny little columns, each 20 pixels wide.

Jason Nichols
+2  A: 

When autoresize mode is set to off the column widths will not be adjusted at all when the table is layed out. From JTable's doLayout() documentation:

AUTO_RESIZE_OFF: Don't automatically adjust the column's widths at all. Use a horizontal scrollbar to accomodate the columns when their sum exceeds the width of the Viewport. If the JTable is not enclosed in a JScrollPane this may leave parts of the table invisible.

Try adding the JTable to a JScrollPane and then adding that to the panel.

Adamski