1

如何在netbeans的Jtable单元格中添加按钮???

4

3 回答 3

2

表按钮列显示一种方式。

于 2010-11-29T18:07:32.750 回答
0

您需要添加自定义单元格渲染器,重新定位表格中的一些事件并在按钮状态更改时重新绘制单元格。这很邪恶,很讨厌,但可以做到。

于 2010-11-29T18:37:00.443 回答
0

按钮表示例所示,我们将创建一个扩展JButton和实现的类TableCellRenderer

class ButtonRenderer extends JButton implements TableCellRenderer {

  public ButtonRenderer() {
    setOpaque(true);
  }

  public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else {
      setForeground(table.getForeground());
      setBackground(UIManager.getColor("Button.background"));
    }
    setText((value == null) ? "" : value.toString());
    return this;
  }
}

然后,您还需要为该列创建一个单元格编辑器。

class ButtonEditor extends DefaultCellEditor {
  protected JButton button;

  private String label;

  private boolean isPushed;

  public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
      }
    });
  }

  public Component getTableCellEditorComponent(JTable table, Object value,
      boolean isSelected, int row, int column) {
    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());
    } else {
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());
    }
    label = (value == null) ? "" : value.toString();
    button.setText(label);
    isPushed = true;
    return button;
  }

  public Object getCellEditorValue() {
    if (isPushed) {
      // 
      // 
      JOptionPane.showMessageDialog(button, label + ": Ouch!");
      // System.out.println(label + ": Ouch!");
    }
    isPushed = false;
    return new String(label);
  }

  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }

  protected void fireEditingStopped() {
    super.fireEditingStopped();
  }
}

然后,我们将设置 的实例ButtonRender作为该列的单元格渲染,并将 ButtonEditor 的实例设置为单元格编辑器。

\\"Button" is the column name
table.getColumn("Button").setCellRenderer(new ButtonRenderer());
table.getColumn("Button").setCellEditor(
    new ButtonEditor(new JCheckBox()));

提供的链接中的示例具有完整的可运行示例。

于 2010-11-30T09:52:09.920 回答