How to change column width of a table
        Posted  
        
            by vybhav
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by vybhav
        
        
        
        Published on 2010-04-08T13:49:00Z
        Indexed on 
            2010/04/08
            13:53 UTC
        
        
        Read the original article
        Hit count: 404
        
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();
   }
}
© Stack Overflow or respective owner