views:

40

answers:

2

Developing a desktop application based on Java + Swing I faced the problem of creating a radio button which instead of text next to it, should have and image or, say, another widget like a spinner.

Clicking on the image or the spinner should select also the corresponding radioButton.

Is it possible? if so, how?

+2  A: 

Well, there is a constructor for JRadioButton that takes an Icon. You can use that to make it have an icon next to it.

JRadioButton(Icon icon)

-- Creates an initially unselected radio button with the specified image but no text.

Otherwise, it is fairly easy to make the JRadioButtons text empty, and place another component next to it. Then you will need to add a Listener to that component, so that the JRadioButton gets clicked if the other component gets clicked.

jjnguy
Have you tried that constructor? It seems to replace the original radio button image instead of adding the icon next to it (see the evaluation in another answer) (-1). Approach with another component would probably work well (+1)
Touko
+1  A: 

To me, the JRadioButton with icon given for constructor doesn't seem to work; it replaces the "native radio button icon" with given icon. I think to original asked wanted for radio button with icon in addition to the "radio button icon".

There has been some debate on the behaviour at Sun bug database with Bug #4177248 but no changes have been made.

Instead, one could try JRadioButtonMenuItem, even though there will probably be some non-wanted behaviour with that?

Short evaluation for both JRadioButton and JRadioButtonMenuItem:

public class IconRadioButtonEval {
    public static void main(String[] args) throws Exception {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        // Use some arbitrary working URL to an icon
        URL url =
                new URL(
                        "http://mikeo.co.uk/demo/sqlspatial/Images/RSS_Icon.png");
        Icon icon = new ImageIcon(url);
        JRadioButton button = new JRadioButton(icon);
        panel.add(new JLabel("RadioButton with icon:"));
        panel.add(button);
        panel.add(new JLabel("RadioButtonMenuItem with icon:"));
        panel.add(new JRadioButtonMenuItem(icon));

        frame.getContentPane().add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

Justin's suggestion for another component next to JRadioButton with empty string should probably work well in most cases.

Touko