Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TableModel vs ColumnModel: who owns the column value?

Tags:

java

swing

jtable

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?

like image 698
Gili Avatar asked Sep 12 '10 18:09

Gili


People also ask

What does JTable do?

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 .

How to implement table in Java?

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.

What is table model in Java?

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);


1 Answers

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.

like image 145
Gili Avatar answered Oct 14 '22 10:10

Gili