about column's width of a JTable in a JScrollPane

user415726 picture user415726 · Aug 10, 2010 · Viewed 14.7k times · Source

i want to set each column of a JTable in a JScrollPane with a fixed num width, but i cannot do it with infoTable.getColumnModel().getColumn(0).setPreferredWidth(10); i use the default layout of JScrollPane and add the table with the scrollPane's setViewPortView(infoTable) in j2se 1.4. How can i get this done? here is my code

private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
public TableFrame() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(
        new java.awt.Color(0, 0, 0)));

    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    this.setSize(new Dimension(600, 600));
    this.jScrollPane1.setSize(500, 500);
    this.getContentPane().add(this.jScrollPane1, BorderLayout.CENTER);
    this.getContentPane().add(this.jButton1, BorderLayout.WEST);
    table = new JTable(new javax.swing.table.DefaultTableModel(100, 2));
    this.jScrollPane1.setViewportView(table);
    table.getColumnModel().getColumn(0).setWidth(10);
}

ps. Thx for replying I need the column can be dragged to resize, so i cannot set the max and min size

Answer

YoK picture YoK · Aug 10, 2010

Also set min and max width of column same as set with setPreferredWidth.

infoTable.getColumnModel().getColumn(0).setMinWidth(10);
infoTable.getColumnModel().getColumn(0).setMaxWidth(10);
infoTable.getColumnModel().getColumn(0).setPreferredWidth(10);