In an example below a window displays a table, containing window itself width. When window is resized, the value of it’s width is reflecting the current truth.
How this can be? How Swing informed a table, that it should rerequest model? Or maybe model is receiving information that value was changed?
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);
}
});
}
}
JTable is just a view which means it does not hold any values. A will generate an exception for you to let you see the whole trace:
Repaint of the frame will eventually trigger repaint of the table. Table model will be used to get a value needed to repaint certain cell.