JTable中向某一列添加JRadioButton

时间:2022-07-25 04:51:28

定义自己的渲染器

class RadioButtonRenderer implements TableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        if (value == null) {
            return null;
        }
        return (Component) value;
    }
}


 

class RadioButtonEditor extends DefaultCellEditor {

    private JRadioButton button;

    public RadioButtonEditor(JCheckBox checkBox) {
        super(checkBox);
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected, int row, int column) {
        if (value == null) {
            return null;
        }
        button = (JRadioButton) value;
        return (Component) value;
    }

    public Object getCellEditorValue() {
        return button;
    }
}

    public void loadtable() {
        DefaultTableModel model = ((DefaultTableModel) jTable1.getModel());
        model.setRowCount(0);
        int countRows = jTable1.getRowCount();//获取当前表格总行数
        jTable1.setRowHeight(25);

        Vector dataVector = new Vector();
        
        for(int i=0; i<5; i++) {
            Vector data = new Vector();
            data.add("开关" + i);
            final JRadioButton btn = new JRadioButton();
            btn.setText("关闭");
            btn.setSelected(false);
            
            btn.addItemListener(new ItemListener() {

                @Override
                public void itemStateChanged(ItemEvent e) {
                    if(btn.isSelected()) {
                        btn.setText("打开");
                    } else {
                        btn.setText("关闭");
                    }
                }
            });
            
            data.add(btn);
            dataVector.add(data);
        }


        Vector columnIdentifiers = new Vector();
        columnIdentifiers.add("测试");
        columnIdentifiers.add("测试1");

        model.setDataVector(dataVector, columnIdentifiers);

        jTable1.setModel(model);
        jTable1.getColumn("测试1").setCellEditor(new RadioButtonEditor(new JCheckBox()));
        jTable1.getColumn("测试1").setCellRenderer(new RadioButtonRenderer());
//        //设置表格的列宽
//        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
//        jTable1.getColumn("测试1").setPreferredWidth(80);
//        jTable1.getColumn("测试1").setMinWidth(80);
//        jTable1.getColumn("测试1").setMaxWidth(80);
    }

 

最终效果图:
JTable中向某一列添加JRadioButton