开发者

JTable Madness?

I've been reading the Swing tutorial "How to Use Tables", and although it has been very informative for the JTable newbie, I am instantly hitting roadblocks the second I try to veer away from the examples and strike out on my own.

So, if you want your Swing app to have a nifty, custom table, it looks like their are several core classes you'll be working with at the very least:

  • JTable
  • TableModel
  • TableModelListener
  • T开发者_运维问答ableModelEvent
  • TableColumnModel
  • TableColumnModelListener
  • TableColumnModelEvent
  1. Just from reading the tutorials and JavaDocs, it is not obvious to me what the difference is between a TableModel and a TableColumnModel, and how they relate to each other. Obviously, the column model pertains just to a single column or all the columns (?), whereas the table model is more general. But how do they relate to one another? What areas of responsibility does each one handle? Does TableModel manage, control or somehow contain the TableColumnModel?

  2. Closely related to the first question, in which model do I specify cell editors and renderers?

  3. I assume that, for each of these objects I should subclass/implement them so I can customize them for my project. Is that the generally-accepted way of customizing tables (subclassing the JTable "core" classes), or are these powerful enough to support any kind of table creation?


Usually, you just define a TableModel (by subclassing AbstractTableModel), and construct a JTable instance with this table model as argument.

If you implement getColumnClass() correctly in your table model, JTable will automatically choose an appropriate renderer for each of your column. If some cells are editable (you tell by overriding isCellEditable() in the table model), the appropriate cell editor will also be associated with the column. You'll have to trigger events (using one of the fireXxx methods in AbstractTableModel) when the model changes.

Of course, if you have special objects in your cells (i.e. something other than String, Boolean, Integer, etc.), you'll have to associate a renderer to a column (and an editor if the cells in these cells are editable). This is done by setting the renderer/editor on the column of the column model. The column model is automatically created by the JTable from the table model, though. You usually don't have to creat one by youself.

So, to answer your specific questions:

  1. TableModel is used to hold the data displayed in the JTable. You must implement it yourself. TableColumnModel is automatically created by the JTable and is typically used to associate a renderer and editor to specific columns.
  2. If you want a specific renderer for the nth column, you get the nth column from the column model of the JTable, and you set a renderer on this column.
  3. Usually subclassing AbstractTableModel is sufficient.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜