开发者

Rich swing radiobutton

Developing a desktop application bas开发者_Python百科ed 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜