【发布时间】:2015-04-01 14:09:53
【问题描述】:
您好,我一直在使用 javax swing,但遇到了一个奇怪的问题并让我质疑。 例如,我可以:
JTable table = new JTable();
// Indeed, 2 different objects:
// The TableModel (which, i think is supposed to contain rows and columns?
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
// And the column model, supposed to define the columns of a table?
TableColumnModel tcm = table.getColumnModel();
// I can add columns to my table in two different manners
dtm.addColumn("A Column");
// or
TableColumn column = new TableColumn();
column.setHeaderValue("Another column");
column.setWidth(120);
column.setMinWidth(120);
column.setMaxWidth(120);
tcm.addColumn(column);
// And notice that both commands will add a column in the table
// So our table model should now have 2 columns.
// But does it?
System.out.println(dtm.getColumnCount()); // outputs 1;
System.out.println(tcm.getColumnCount()); // outputs 2;
System.out.println(table.getColumnCount()); // outputs 2;
// The visual shows 2 columns, but the model has only 1.
从中我可以看出 JTable 使用 tableColumnModel 并且 tableColumnModel 将所有列添加到 tableModel 中,但是,当我向 TableModel 添加列时,它会添加到表中,但 tableModel 仍然过时。
现在,问题是:通过 columnModel 添加列真的很有趣,因为我可以在那里定义大小、布局、可编辑选项,但是这样我不能从 tableModel 向它添加任何数据,因为该列没有'不会出现在 tableModel 上。 对此有什么想法吗?
【问题讨论】:
-
发布无效代码示例是对任何浪费时间阅读您的问题的人的侮辱。您不声明或初始化变量“列”,这是最重要的。
-
@LorenzoGatti 我做到了,我只是拼错了 Ctrl+V'ng 一个 sn-p 的声明。顺便说一句。
-
这是SO posting的副本