在下面的示例中,窗口显示了一个表格,其中包含窗口本身的宽度。当窗口调整大小时,它的宽度值反映了当前的事实。
这怎么可能?Swing 如何通知表,它应该重新请求模型?或者模型可能正在接收值已更改的信息?
public class JTableDynamicUpdate extends JFrame {
private AbstractTableModel tableModel = new AbstractTableModel() {
private String[] columnNames = new String[] {"Parameter", "Value"};
public String getColumnName(int column) {
return columnNames[column];
};
@Override
public int getRowCount() {
return 1;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if( rowIndex == 0 ) {
if( columnIndex == 0 ) {
return "Window width:";
}
else if( columnIndex==1) {
return getSize().width;
}
}
throw new IndexOutOfBoundsException();
}
};
private JTable table = new JTable(tableModel);
private JScrollPane tableScroll = new JScrollPane(table);
private Container contentPane = getContentPane();
{
contentPane.setLayout(new BorderLayout());
contentPane.add(tableScroll, BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTableDynamicUpdate frame = new JTableDynamicUpdate();
frame.pack();
frame.setVisible(true);
}
});
}
}