سؤال

كيفية إضافة زر في خلية Jtable في NetBeans ؟؟؟

هل كانت مفيدة؟

المحلول

تحتاج إلى إضافة عارض الخلايا المخصصة ، وإعادة استهداف بعض الأحداث من الجدول وخلايا إعادة التدوير عندما تتغير حالة الزر. إنه شرير ، إنه أمر سيء ، ولكن يمكن القيام به.

نصائح أخرى

عمود زر الجدول يظهر طريقة واحدة.

كما هو موضح في مثال جدول الزر سنقوم بإنشاء فصل يمتد 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 كما تقدم الخلية لهذا العمود ومثيل زر كمحرر الخلية.

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

ال مثال في الرابط المقدم له مثال كامل قابل للتشغيل.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top