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
In general you only need to set the preferred width. But to accomplish your goal you first you need to know the default widths and how they are used to determine the actual default size:
min = 15
preferred = 75
max = Integer.MAX_VALUE
So you can't use 10 unless you also change the minimum width.
Lets take a simple case where your preferred width is 25 for column 1 and the scrollpane is 500. Therefore the preferred width of the two columns is 100 (25 + 75). The extra 400 pixels is allocated evenly between the two columns so the columns will be displayed at 225 (25 + 200) and 275 (75 + 200). Therefore by default you can't just display the first column at 25 pixels unless you also set the second column to 475.
If you want all columns to be displayed at their preferred widths then you need to use:
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );