• title: JTableのセル中にJRadioButtonを配置 tags: [JTable, JRadioButton, TableCellRenderer, TableCellEditor, JPanel, ActionListener] author: aterai pubdate: 2009-12-21T00:36:55+09:00

概要

JTableのセル中に複数のJRadioButtonを配置します。JTableExamples2を元に修正を行っています。

サンプルコード

class RadioButtonsPanel extends JPanel {
  private static final String OSNAME = System.getProperty("os.name");
  private final String[] answer = { "A", "B", "C" };
  public JRadioButton[] buttons;
  public ButtonGroup bg = new ButtonGroup();
  public RadioButtonsPanel() {
    super();
    setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    initButtons();
  }
  protected void initButtons() {
    bg = new ButtonGroup();
    buttons = new JRadioButton[answer.length];
    for(int i=0;i<buttons.length;i++) {
      buttons[i] = new JRadioButton(answer[i]);
      buttons[i].setActionCommand(answer[i]);
      buttons[i].setFocusable(false);
      buttons[i].setRolloverEnabled(false);
      add(buttons[i]);
      bg.add(buttons[i]);
    }
  }
  protected void updateSelectedButton(Object v) {
    if("Windows 7".equals(OSNAME)) { //Windows aero?
      removeAll();
      initButtons();
    }
    if("A".equals(v)) {
      buttons[0].setSelected(true);
    }else if("B".equals(v)) {
      buttons[1].setSelected(true);
    }else{
      buttons[2].setSelected(true);
    }
  }
}
View in GitHub: Java, Kotlin
class RadioButtonsRenderer extends RadioButtonsPanel implements TableCellRenderer {
  public RadioButtonsRenderer() {
    super();
    setName("Table.cellRenderer");
  }
  @Override public Component getTableCellRendererComponent(JTable table,
        Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    updateSelectedButton(value);
    return this;
  }
}
class RadioButtonsEditor extends RadioButtonsPanel implements TableCellEditor {
  public RadioButtonsEditor() {
    super();
    ActionListener al = new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
      }
    };
    for(AbstractButton b: buttons) b.addActionListener(al);
  }
  @Override public Component getTableCellEditorComponent(JTable table,
        Object value, boolean isSelected, int row, int column) {
    updateSelectedButton(value);
    return this;
  }
  @Override public Object getCellEditorValue() {
    return bg.getSelection().getActionCommand();
  }

  //Copied from AbstractCellEditor
  //protected EventListenerList listenerList = new EventListenerList();
  transient protected ChangeEvent changeEvent = null;
//......

解説

上記のサンプルでは、JRadioButton3つ配置したJPanelを、CellRendererCellEditor用に2つ用意しています。CellEditor内の各JRadioButtonには、クリックされたら編集を終了して更新をコミットするためのActionListenerを追加しています。

参考リンク

コメント