[英]Understanding How to Add A JButton to a JTable
我正在尝试在JTable中实现一些按钮。 我一直在看这个例子 。
我不明白的是这个构造函数:
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
用法更多地是使用Button的技巧,因为它仅接受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));
这是因为class ButtonEditor extends DefaultCellEditor
,并且在您的示例中DefaultCellEditor
构造函数看起来像是DefaultCellEditor(JCheckBox checkBox)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.