What's the difference between JTable.getModel().getColumnName()
and JTable.getColumnModel().getColumn(index).getHeaderValue()
? The two don't seem to share any data. My guess is that TableModel.getColumnName()
indicates the textual representation of a column while TableColumn.getHeaderValue()
and TableColumn.getHeaderRenderer()
determine what the column looks like (it doesn't need to be plain text).
What guarantees that the two are kept in sync? What happens if the two conflict?
The JTable is used to display and edit regular two-dimensional tables of cells. See How to Use Tables in The Java Tutorial for task-oriented documentation and examples of using JTable .
JTable(): A table is created with empty cells. JTable(int rows, int cols): Creates a table of size rows * cols. JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column defines the column names.
The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model. The JTable can be set up to display any data model which implements the TableModel interface with a couple of lines of code: TableModel myData = new MyTableModel(); JTable table = new JTable(myData);
If a JTable is constructed with a TableModel but without a TableColumnModel the JTable will create a TableColumnModel using createDefaultColumnModel() and set autoCreateColumnsFromModel to true. When this property is true, the JTable will populate the TableColumnModel with values from the TableModel.
No one seems to guarantee that the two are kept in sync. Case in point, JTable.getColumnName() will return the TableModel column name regardless of what the TableColumnModel actually displays on the screen.
Another interesting thing I noticed is that TableModel is limited to String columns whereas TableColumnModel allows you to pass any Object to the TableCellRenderer. The Javadoc says that the values are restricted to Strings but in fact this is implementation-specific. Nothing prevents you from writing an implementation that uses a JComponent value.
In summary: TableColumnModel is the ultimate owner of column values. TableColumnModel only asks TableModel for values only if it doesn't already have one. For example, in the case where you pass a column into JTable.addColumn() without specifying a header value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With