编辑单元格时切换值
我有一个 JTable,它使用自定义 TableModel 来显示一系列对象实例。 getValueAt(int row, int column)
内部有一个 switch case,用于根据给定属性返回值(见下文)。一个 return 语句涉及返回值 1/0 作为真/假。
有没有办法可以修改此 TableModel,以便在编辑单元格时显示 1/0?
public Object getValueAt(int row, int column) {
User user = (User)dataVector.get(row);
switch (column) {
case ID_INDEX:
return user.getId();
case USERNAME_INDEX:
return user.getUserName();
case PASSWORD_INDEX:
return "****";
case ACTIVATED_INDEX:
return (user.getActivated())?"true":"false";
default:
return new Object();
}
}
I have a JTable which uses a custom TableModel to display a series of object instances. There's a switch case inside getValueAt(int row, int column)
to return values according to given attributes (see below). One return statement involves returning a value of 1/0 as true/false.
Is there a way that I can modify this TableModel so that it displays a 1/0 when a cell is edited?
public Object getValueAt(int row, int column) {
User user = (User)dataVector.get(row);
switch (column) {
case ID_INDEX:
return user.getId();
case USERNAME_INDEX:
return user.getUserName();
case PASSWORD_INDEX:
return "****";
case ACTIVATED_INDEX:
return (user.getActivated())?"true":"false";
default:
return new Object();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
的默认渲染器和编辑器>Boolean
是一个JCheckBox
。考虑使用替代方案,
附录:例如,
DefaultTableModel
不会覆盖getColumnClass()
,并且AbstractTableModel
只是返回Object.class< /代码>。您的
TableModel
应相应地覆盖getColumnClass()
:The default renderer and editor for
Boolean
is aJCheckBox
. Consider usingAlternatively,
Addendum: As an example,
DefaultTableModel
does not overridegetColumnClass()
, andAbstractTableModel
simply returnsObject.class
. YourTableModel
should overridegetColumnClass()
accordingly:您需要查看
TableCellRenderer
和TableCellEditor
:TableCellRenderer
负责在未编辑时渲染单元格数据,其中TableCellEditor
负责提供用于编辑单元格值的组件。因此,您可以用两种不同的方式表示数据,具体取决于数据是正在编辑还是仅按正常方式呈现。然而,您应该考虑到,如果您从 getValueAt() 方法返回布尔类型,您的 JTable 应该自动呈现一个 JCheckBox,当单元格处于编辑模式时,可以像往常一样通过单击它来更改 JCheckBox 值。为此,只需返回:
You need to have a look at
TableCellRenderer
andTableCellEditor
:A
TableCellRenderer
is responsible for rendering cell data when it is not being edited, where as aTableCellEditor
is responsible for providing a component used to edit the value of a cell. You can therefore represent the data in two separate ways depending on whether it is being edited or just rendered as per normal.You should however consider that if you return a Boolean type from the getValueAt() method, your JTable should automatically render a JCheckBox, when the cell is in edit mode, the JCheckBox value can be changed by clicking on it as usual. To do this just return: