【发布时间】:2017-12-17 00:58:47
【问题描述】:
我正在尝试将 JComponents 添加到 JTable 单元中。我要实现 CellRenderer 还是 CellEditor?
【问题讨论】:
我正在尝试将 JComponents 添加到 JTable 单元中。我要实现 CellRenderer 还是 CellEditor?
【问题讨论】:
您需要的是一个自定义编辑器,它将返回 JComboBox(或您想要使用的任何组件)。您应该查看Sun tutorial for JTable,它包含一个关于如何使用 JComboBox 作为编辑器的示例。如果你也想使用 JComboBox 作为渲染器,本教程也适用。
【讨论】:
您也可以通过将 JComboBox(或 JCheckBox 或 JTextField)的实例传递给构造函数来使用 DefaultCellEditor。
【讨论】:
1- 创建一个JCombobox 并在其中插入您想要的信息,如下所示:
JComboBox<String> sport = new JComboBox<String>();
sport.addItem("foot");
sport.addItem("hand bool");
sport.addItem("****");
2- 创建一个JTable 并为此表设置一个表模式,类似于:
Vector<String> title = new Vector<String>
title.add("id");
title.add("sport");
Vector<Vector<String>> rows = new Vector<Vector<String>>();
rows.addItem("1");
rows.addItem("2");
JTable table = new JTable(rows, title);
3- 你把 JComboBox 放在 JTable 单元格中,如下所示:
table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(sport));
【讨论】: