我正在尝试在 JTable 中实现一些按钮。我一直在看 this example .
我不明白的是这个构造函数:
public ButtonEditor(JCheckBox checkBox) {
super(checkBox);
button = new JButton();
button.setOpaque(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
JCheckBox 有什么关系?任何地方都没有显示 JCheckBox,它似乎也与示例无关。 TIA。
最佳答案
此处的 DefaultCellEditor
用法更多的是使用按钮的 hack,因为它仅接受 JCheckBox
、JComboBox
和 JTextField
.
如果你真的想实现JButton
,你也可以这样做,
class ButtonEditor extends AbstractCellEditor
implements javax.swing.table.TableCellEditor,
javax.swing.tree.TreeCellEditor
此外,您可以更新您的实现,以使用带有 JButton
作为参数或默认构造函数的构造函数,
方法 1
public ButtonEditor() {
super(new JCheckBox());
button = new JButton();
button.setOpaque(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
并且可以通过以下方式访问:
table.getColumn("Button").setCellEditor(
new ButtonEditor());
方法 2
public ButtonEditor(JButton button) {
super(new JCheckBox());
this.button = button;
button.setOpaque(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
这种方法在单元格编辑器之外也提供了更好的清晰度和按钮组件的使用,
JButton button=new JButton();
table.getColumn("Button").setCellEditor(
new ButtonEditor(button));
关于java - 了解如何将 JButton 添加到 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48114768/