[英]Is it possible to display different data in JTable fields using one object?
Being that what gets displayed in the JTable is the stored object's toString
, is it somehow possible to display other information? 在JTable中显示的是存储对象的
toString
,是否有可能显示其他信息?
For example, if I have a simple user object like this: 例如,如果我有一个简单的用户对象,例如:
class User {
private String firstname;
private String lastname;
...
}
Can I display the first
and last
name properties in their own column in a JTable? 我可以显示
first
和last
在自己的列名的属性JTable中?
Like this: 像这样:
Currently, I'm storing the string properties of the User
object in the JTable
rather than the User
object itself. 当前,我将
User
对象的字符串属性存储在JTable
而不是User
对象本身。
// where first/lastname are the strings retrieved
// via getFirstname() and getLastname() on the User object.
model.addRow(new Object[] {first, last });
However, the problem with this is all the book keeping involved anytime I need to retrieve and build the Object that the user clicks on in the JTable. 但是,与此相关的问题是,每当我需要检索和构建用户在JTable中单击的Object时,涉及的所有书籍都将保留下来。 Is it possible to store the User object in the JTable, but have it display different properties depending on the column it's in?
是否可以将User对象存储在JTable中,但是根据它所在的列,它是否显示不同的属性?
Yes it is. 是的。 Just define a different TableCellRenderer to each column:
只需为每列定义一个不同的TableCellRenderer :
User user = new User("Zack", "Yoshyaro");
DefaultTableModel model = new DefaultTableModel(new Object[]{"First", "Last"}, 0);
model.addRow(new Object[]{user, user}); // note user must be added for each column, but it's the same object
JTable table = new JTable(model);
TableColumn firstName = table.getColumn("First");
firstName.setCellRenderer(...); // a cell renderer that shows user.getFirstName();
TableColumn lastName = table.getColumn("Last");
lastName.setCellRenderer(...); // a cell renderer that shows user.getLastName();
See Using custom Renderer section in How to Use Tables tutorial. 请参阅“ 如何使用表”教程中的“ 使用自定义渲染器”部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.