概要

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

サンプルコード

class RadioButtonsPanel extends JPanel {
  private final String[] answer = {Answer.A.toString(), Answer.B.toString(), Answer.C.toString()};
  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 (v instanceof Answer) {
      //if ("Windows 7".equals(OSNAME)) { //Windows aero?
      removeAll();
      initButtons();
      //}
      switch ((Answer) v) {
        case A:
          buttons[0].setSelected(true);
          break;
        case B:
          buttons[1].setSelected(true);
          break;
        case C:
          buttons[2].setSelected(true);
          break;
        default:
          break;
      }
    }
  }
}
view all
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には、クリックされたら編集を終了して更新をTableModelにコミットするためのActionListenerを追加しています。

参考リンク

コメント