我没有看到你看到的行为。每次按下按钮时,以下程序都会显示正确的宽度。您必须显示另一个表或表列模型的列的宽度。
public class TableColumnTest extends JFrame {
private JTable table;
public TableColumnTest() {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
table = new JTable(5, 4);
p.add(new JScrollPane(table), BorderLayout.CENTER);
JButton b = new JButton("Test");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
displayWidths();
}
});
p.add(b, BorderLayout.SOUTH);
add(p);
pack();
}
private void displayWidths() {
for (int i = 0; i < table.getColumnCount(); i++) {
TableColumn column = table.getColumnModel().getColumn(i);
System.out.println("Width of column " + i + " : " + column.getWidth());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TableColumnTest().setVisible(true);
}
});
}
}