JTable:RadioButton列:只选择一个单选按钮

时间:2018-03-12 17:42:13

标签: java jtable

Java 1.8,

这里我的radioButton渲染:

public class RadioButtonCellEditorRenderer extends AbstractCellEditor
        implements TableCellRenderer, TableCellEditor, ActionListener {

    private JRadioButton radioButton;

    public RadioButtonCellEditorRenderer() {
        this.radioButton = new JRadioButton();
        radioButton.addActionListener(this);
        radioButton.setOpaque(false);
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        radioButton.setSelected(Boolean.TRUE.equals(value));
        return radioButton;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        radioButton.setSelected(Boolean.TRUE.equals(value));
        return radioButton;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        stopCellEditing();
    }

    @Override
    public Object getCellEditorValue() {
        return radioButton.isSelected();
    }

}

在这里我如何使用这个类:

private void initTable() {
    TableColumn tableColumn = null;
    for (int i = 0; i < searchResultTable.getColumnCount(); i++) {
        tableColumn = searchResultTable.getColumnModel().getColumn(i);
        if (i == 0) {// check box
            tableColumn.setMaxWidth(40);
            tableColumn.setCellEditor(new RadioButtonCellEditorRenderer());
            tableColumn.setCellRenderer(new RadioButtonCellEditorRenderer());
        } 
    }
}

结果如下:

enter image description here

如您所见,我可以选择多个单选按钮。但我需要选择一个单选按钮。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

将单选按钮添加到组

所以我不确定你的程序是如何工作的,这是一个镜头

public JRadioButton getRadioButton(){ return radioButton; }

还要将它添加到您的RadioButtonCellEditorRenderer类

append

答案 1 :(得分:0)

此处的单选按钮组缺少您。请参阅以下示例。尝试使用此示例并修复您的问题。希望这会对你有所帮助。

 ButtonGroup bG = new ButtonGroup();

public RadioButtonCellEditorRenderer() {
    this.radioButton = new JRadioButton();
    radioButton.addActionListener(this);
    radioButton.setOpaque(false);
    bG.add(radioButton);//add this line
}