1

I used this guide in order to make JTable that would handle radio buttons. Works fine except i need to enable a default enabled button.

there can be n rows. I've tried to enable it through the default table model, the Object[][], the table, and i tried enabling the button before adding it to the Object[][]. I couldn't figure out how(if it is possible) to do it with the buttongroup.

to find the default enabled button i have to compare the button text to a string(this part works).

tenorsax
  • 21,123
  • 9
  • 60
  • 107
Phox
  • 101
  • 1
  • 1
  • 10
  • never-ever store components in a tableModel, that's completely wrong ... Instead, store _data_ that can be rendered by a custom rendering component – kleopatra Aug 23 '12 at 08:03

2 Answers2

6

Not sure that I am interpreting the question correctly. You can use JRadioButton constructor to set selection, for example the snippet (based on OP code sample) will set selected button "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" });

You can also change selection like this:

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

You can also use ButtonGroup.setSelected() method.

EDIT: eliminate components from model

The model should contain data rather than components. Storing components in the model defeats the idea of renderers and editors. For more details see Editors and Renderers and Swing Models and Renderers. Check out the following example the mimics button group behavior in the model:

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());
        }
    }   
}
tenorsax
  • 21,123
  • 9
  • 60
  • 107
  • Oh god I am an idiot! I was using setEnabled instead of setSelected... Working with java guis for a week and a half has fried my brain. – Phox Aug 22 '12 at 18:18
  • -1 for storing components in the model (the OP copying an old, incorrect example is no excuse to repeat it ;-) – kleopatra Aug 23 '12 at 08:04
  • @kleopatra agree! I amended the answer with an example of group like implementation in the model. – tenorsax Aug 24 '12 at 00:49
  • @Phox please checkout my last update that eliminates components from the model. – tenorsax Aug 24 '12 at 00:50
  • I plan to revisit the code and clean it up. So I'll try fix the radio buttons to use data rather than the components – Phox Aug 24 '12 at 12:33
0

Did you try to repaint() your JTable ?

Is the checkbox always unchecked or is there some case in which it is not ?

Hovercraft Full Of Eels is right : could you post a bunch of your code ?

Benj
  • 1,184
  • 7
  • 26
  • 57
  • turns out i royally messed up and used setEnabled instead of setSelected. It was completely a goof on my part. – Phox Aug 22 '12 at 18:20
  • :p no problem, we all do this sometimes ! – Benj Aug 22 '12 at 18:30
  • I was wrong too, the repaint() solution worked for a project of mine where i was generating "picture" buttons, but (what an idiot) you are in a totally different case ! – Benj Aug 22 '12 at 20:50
  • with a well-behaved (read: correctly notifying) model a repaint is _never_ needed. If that seems to resolve update problems, something is wrong elsewhere – kleopatra Aug 23 '12 at 08:05