Search code examples
javaimageswingtextjradiobutton

How to set image and text on JRadioButton?


I am using Swing and JRadioButton in my application. I need to set image and text on my button. For that I am using this:

JRadioButton button1 = new JRadioButton("text", iconpath, false);

But what it giving output is it's hiding radio button and just showing the image.

How to over come this problem, any suggestion? and can we Create something for similar problem for JCheckbox too?


Solution

  • Setting the icon of a JRadioButton or JCheckBox replaces the default glyph used by these controls - I know, annoying.

    The simplest solution is to simply create a JLabel which can be associated with the JRadioButton, perhaps using some kind of Map to maintain the linkage between

    A more, long term solution, might be to create a custom component which marries the concept into a custom and re-usable component, for example...

    public class XRadioButton extends JPanel {
    
        private JRadioButton radioButton;
        private JLabel label;
    
        public XRadioButton() {
            setLayout(new GridBagLayout());
            add(getRadioButton());
            add(getLabel());
        }
    
        public XRadioButton(Icon icon, String text) {
            this();
            setIcon(icon);
            setText(text);
        }
    
        protected JRadioButton getRadioButton() {
            if (radioButton == null) {
                radioButton = new JRadioButton();
            }
            return radioButton;
        }
    
        protected JLabel getLabel() {
            if (label == null) {
                label = new JLabel();
                label.setLabelFor(getRadioButton());
            }
            return label;
        }
    
        public void addActionListener(ActionListener listener) {
            getRadioButton().addActionListener(listener);
        }
    
        public void removeActionListener(ActionListener listener) {
            getRadioButton().removeActionListener(listener);
        }
    
        public void setText(String text) {
            getLabel().setText(text);
        }
    
        public String getText() {
            return getLabel().getText();
        }
    
        public void setIcon(Icon icon) {
            getLabel().setIcon(icon);
        }
    
        public Icon getIcon() {
            return getLabel().getIcon();
        }
    
    }