了解如何将 JButton 添加到 JTable
Understanding How to Add A JButton to a JTable
我正在尝试在我的 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.
这是因为 class ButtonEditor extends DefaultCellEditor
,而您示例中 DefaultCellEditor
的构造函数看起来像这样 DefaultCellEditor(JCheckBox checkBox)
此处的 DefaultCellEditor
用法更像是使用 Button 的技巧,因为它只接受 JCheckBox
、JComboBox
和 JTextField
。
如果你真的想为JButton
实现,你也可以这样做,
class ButtonEditor extends AbstractCellEditor
implements javax.swing.table.TableCellEditor,
javax.swing.tree.TreeCellEditor
否则,您可以更新您的实现,以使用带有 JButton
作为参数或默认构造函数的构造函数,
方法一
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());
方法二
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));
我正在尝试在我的 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.
这是因为 class ButtonEditor extends DefaultCellEditor
,而您示例中 DefaultCellEditor
的构造函数看起来像这样 DefaultCellEditor(JCheckBox checkBox)
此处的 DefaultCellEditor
用法更像是使用 Button 的技巧,因为它只接受 JCheckBox
、JComboBox
和 JTextField
。
如果你真的想为JButton
实现,你也可以这样做,
class ButtonEditor extends AbstractCellEditor
implements javax.swing.table.TableCellEditor,
javax.swing.tree.TreeCellEditor
否则,您可以更新您的实现,以使用带有 JButton
作为参数或默认构造函数的构造函数,
方法一
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());
方法二
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));