簡體   English   中英

了解如何向JTable添加JButton

[英]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的技巧,因為它僅接受JCheckBoxJComboBoxJTextField

如果您確實想為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM