java - JTable中的JComboBox不保存选择
问题描述
我有一个包含一个Name
和Choice
列的 JTable。我希望该Choice
列包含一个JComboBox
对每一行都有相同选择的组件,尽管允许对每个唯一行进行独立选择。
目前,与JComboBox
列内的交互允许出现下拉菜单以进行选择;但是,没有保存任何选择。
相反,所做的选择会迁移到JComboBox
我点击的任何地方。例如,我单击第一行JComboBox
并选择“Choice B”,但所有选项仍显示为“Choice A”。直到我单击另一行时JComboBox
,才会出现下拉菜单,并突出显示“Choice B”选项。
该表使用的代码如下:
final String[] choices = new String[]{"Choice A", "Choice B", "Choice C"};
final Collection<String> mockData = Arrays.asList("First", "Second", "Third", "Fourth", "Fifth", "Sixth");
table.setModel(new MasterTableModel(mockData.stream().map(s -> {
return new Object[]{s, new JComboBox<>(choices)};
}).collect(Collectors.toSet())));
table.setDefaultEditor(JComboBox.class, new DefaultCellEditor(new JComboBox<>(choices)));
table.setDefaultRenderer(JComboBox.class, new MasterTableComboRenderer(table.getDefaultRenderer(JComboBox.class)));
我有三个选择,用于初始化JComboBox
填充Choice
列的 es。我将 设置为实现接口DefaultRenderer
的自定义MasterTableComboRenderer
对象,TableCellRenderer
以便JComboBox
显示为 aComponent
而不是打印对象的地址。它只需要覆盖一个方法:
class MasterTableComboRenderer ...
@Override
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
return value instanceof Component ? (Component) value : renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
最后,MasterTableModel
是 的简单扩展AbstractTableModel
,它定义了列标题[Name, Choice]
并保存了Object[][]
代表JTable
的数据。我已经覆盖isCellEditable
并getColumnClass
如下:
class MasterTableModel...
@Override
public boolean isCellEditable(final int rowIndex, final int columnIndex) {
return getColumnName(columnIndex).equals("Choice");
}
@Override
public Class<?> getColumnClass(final int columnIndex) {
return getValueAt(0, columnIndex).getClass();
}
JComboBox
为了实现保存其选择的功能并且没有将选择突出显示迁移到其他框,我是否缺少一些东西?
解决方案
AJComboBox
不应该存储在TableModel
. 该String
值存储在模型中。
阅读 Swing 教程中关于使用组合框作为渲染器的部分以获取工作示例。
如果您希望渲染器看起来像一个组合框,那么您需要使用组合框作为渲染器。就像是:
class ComboBoxRenderer extends JComboBox implements TableCellRenderer
{
public ComboBoxRenderer()
{
setBorder(null);
}
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
removeAllItems();
addItem( value );
return this;
}
}
推荐阅读
- javascript - 无法弄清楚为什么我的 JavaScript for 循环只循环一次
- python - 将 if 语句的结果打印到原始数据框中
- python - 如何迭代字典项?
- vb.net - VB.NET 中的 curl 请求等效项 - monday.com API
- bash - 选择字符串块
- apache-spark - 有没有一种方法可以在不使用explode函数的情况下展平结构数组的复杂数据类型数组?
- java - 获取错误版本的密钥库。在安卓中
- php - 十月 CMS 安装在 Laravel Homestead 上运行,服务器返回混合的静态资产
- node.js - 您如何进行多个查询并将所有数据发送到模板以在单个 res.render 中进行渲染?
- ios - 如何发布仅适用于 iPhone 而不是 iPad 的应用程序?