java - 在 JTable 中设置默认启用的单选按钮

标签 java swing jtable jradiobutton buttongroup

我用了this指南,以便制作可处理单选按钮的 JTable。工作正常,除了我需要启用默认启用按钮。

可以有n行。我尝试通过默认表格模型、Object[][]、表格启用它,并且我尝试在将按钮添加到 Object[][]< 之前启用它。我无法弄清楚如何(如果可能的话)使用按钮组来做到这一点。

要找到默认启用的按钮,我必须将按钮文本与字符串进行比较(这部分有效)。

最佳答案

不确定我是否正确解释了问题。您可以使用 JRadioButton 构造函数来设置选择,例如片段(基于 OP 代码示例)将设置选定按钮“B”:

dm.setDataVector(new Object[][] { { "Group 1", new JRadioButton("A") },
    { "Group 1", new JRadioButton("B", true) },
    { "Group 1", new JRadioButton("C") },
    { "Group 2", new JRadioButton("a") },
    { "Group 2", new JRadioButton("b") } }, new Object[] {
    "String", "JRadioButton" });

您也可以像这样更改选择:

((JRadioButton) dm.getValueAt(0, 1)).setSelected(true);

您还可以使用 ButtonGroup.setSelected() 方法。

编辑:从模型中删除组件

模型应该包含数据而不是组件。在模型中存储组件违背了渲染器和编辑器的想法。有关详细信息,请参阅 Editors and RenderersSwing Models and Renderers .查看以下模型中模拟按钮组行为的示例:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.table.*;

public class ButtonGroupMockupTest {
    private static void createAndShowGUI() {
        DefaultTableModel model = new DefaultTableModel(new Object[][] {
                { "Group 1", Boolean.FALSE }, { "Group 2", Boolean.FALSE },
                { "Group 3", Boolean.FALSE } },
                new Object[] { "Name", "State" }) {

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int col) {
                if (col == 1)
                    return Boolean.class;
                return super.getColumnClass(col);
            }

            @Override
            public void setValueAt(Object value, int row, int col) {
                super.setValueAt(value, row, col);
                if (col == 1 && value.equals(Boolean.TRUE))
                    deselectValues(row, col);
            }

            private void deselectValues(int selectedRow, int col) {
                for (int row = 0; row < getRowCount(); row++) {
                    if (getValueAt(row, col).equals(Boolean.TRUE)
                            && row != selectedRow) {
                        setValueAt(Boolean.FALSE, row, col);
                        fireTableCellUpdated(row, col);
                    }
                }
            }
        };

        JTable table = new JTable(model);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setDefaultRenderer(Boolean.class, new BooleanRadionRenderer());
        table.setDefaultEditor(Boolean.class, new BooleanRadioEditor());

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JScrollPane(table));

        f.pack();
        f.setLocationByPlatform(true);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    static class BooleanRadionRenderer implements TableCellRenderer, UIResource {
        JRadioButton radioButton;
        Border emptyBorder;

        public BooleanRadionRenderer() {
            radioButton = new JRadioButton();
            radioButton.setHorizontalAlignment(JRadioButton.CENTER);
            radioButton.setBorderPainted(true);
            emptyBorder = BorderFactory.createEmptyBorder(1, 1, 1, 1);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int col) {
            if (isSelected) {
                radioButton.setBackground(table.getSelectionBackground());
                radioButton.setForeground(table.getSelectionForeground());
            } else {
                radioButton.setBackground(table.getBackground());
                radioButton.setForeground(table.getForeground());
            }
            if (hasFocus)
                radioButton.setBorder(UIManager
                        .getBorder("Table.focusCellHighlightBorder"));
            else
                radioButton.setBorder(emptyBorder);

            radioButton.setSelected(((Boolean) value).booleanValue());
            return radioButton;
        }
    }

    static class BooleanRadioEditor extends AbstractCellEditor 
                                    implements TableCellEditor {
        private static final long serialVersionUID = 1L;
        private JRadioButton radioButton;

        public BooleanRadioEditor() {
            radioButton = new JRadioButton();
            radioButton.setHorizontalAlignment(JRadioButton.CENTER);
            radioButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    // prevent deselection to mimic button group
                    if (!radioButton.isSelected())
                        cancelCellEditing();
                    stopCellEditing();
                }
            });
        }

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

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

关于java - 在 JTable 中设置默认启用的单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078648/

相关文章:

java - JRootPane.getName() 返回 Null?

Java JTable获取选中行的数据

java - 没有制表符的空白的正则表达式

java - Scala 中的多值赋值行为

java - 如何在 JLabels 中应用换行符?

Java 实时 JPanel、JLabel + 图像大小调整

java - Spring Webflow中验证后未执行Action类方法

java - 如何从右对齐java中的输出?

java - 在JTable中设置不同颜色的行?

java - 如何设置行数? JTable setRowCount GUI 通过 Jtextfield 和 JButton