TITLE:JTableのセル中にJRadioButtonを配置

Posted by terai at 2009-12-21

JTableのセル中にJRadioButtonを配置

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

  • &jnlp;
  • &jar;
  • &zip;

#screenshot

サンプルコード

class RadioButtonPanel extends JPanel {
  public final JRadioButton[] buttons;
  public final ButtonGroup bg = new ButtonGroup();
  RadioButtonPanel(String[] answer) {
    super();
    setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    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].setEnabled(true);
      add(buttons[i]);
      bg.add(buttons[i]);
    }
  }
}
class RadioButtonEditorRenderer extends AbstractCellEditor
                implements TableCellRenderer, TableCellEditor{
  private final String[] answer = { "A", "B", "C" };
  private final RadioButtonPanel editor;
  private final RadioButtonPanel renderer;
  public RadioButtonEditorRenderer() {
    super();
    this.editor   = new RadioButtonPanel(answer);
    this.renderer = new RadioButtonPanel(answer);
  }
  private void setSelectedButton(RadioButtonPanel p, Object v) {
    if("A".equals(v)) {
      p.buttons[0].setSelected(true);
    }else if("B".equals(v)) {
      p.buttons[1].setSelected(true);
    }else{
      p.buttons[2].setSelected(true);
    }
  }
  @Override public Component getTableCellRendererComponent(
    JTable table, Object value, boolean isSelected,
    boolean hasFocus, int row, int column) {
    setSelectedButton(renderer, value);
    return renderer;
  }
  @Override public Component getTableCellEditorComponent(
    JTable table, Object value, boolean isSelected, int row, int column) {
    setSelectedButton(editor, value);
    return editor;
  }
  @Override public Object getCellEditorValue() {
    return editor.bg.getSelection().getActionCommand();
  }
}

解説

上記のサンプルでは、JRadioButtonを3つ配置したJPanelを、CellRenderer、CellEditor用に二つ用意しています。実際にどのJRadioButtonがクリックされたかなどは、以下のように、JTableに追加したMouseListenerで処理するようになっています。

table.addMouseListener(new MouseAdapter() {
  @Override public void mouseReleased(MouseEvent e) {
    JTable t = (JTable)e.getComponent();
    Point pt = e.getPoint();
    int row  = t.rowAtPoint(pt);
    int col  = t.columnAtPoint(pt);
    if(t.convertRowIndexToModel(row)>=0 &&
      t.convertColumnIndexToModel(col)==1) {
      TableCellEditor ce = t.getCellEditor(row, col);
      //http://tips4java.wordpress.com/2009/07/12/table-button-column/
      ce.stopCellEditing();
      Component c = ce.getTableCellEditorComponent(t, null, true, row, col);
      Point p = SwingUtilities.convertPoint(t, pt, c);
      Component b = SwingUtilities.getDeepestComponentAt(c, p.x, p.y);
      if(b instanceof JRadioButton) ((JRadioButton)b).doClick();
    }
  }
});

参考リンク

コメント