JRadioButton: how to replace text by IconImage?

Jason Rogers picture Jason Rogers · Jul 21, 2011 · Viewed 9.6k times · Source

I want to replace the text in my radio button list by an icon.

I've tried this:

rotateButton = new JRadioButton(rotateIcon.getImage());

But this replaces the radio button and text by the icon. I would like to keep the radio button and display the image.

What should I do?


What I'm currently getting is:

Enter image description here

But I want it to end up with this:

Enter image description here

Answer

Eva picture Eva · Oct 10, 2011

Create a JRadioButton with no text and put a JLabel with the image next to it. You can also create a class to hide complexity.

import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.event.ChangeListener;

public class RadioButtonWithImage extends JPanel {

private JRadioButton radio = new JRadioButton();
private JLabel image;

public RadioButtonWithImage(Icon icon) {
    image = new  JLabel(icon);
    add(radio);
    add(image);
}

public void addToButtonGroup(ButtonGroup group) {
    group.add(radio);
}

public void addActionListener(ActionListener listener) {
    radio.addActionListener(listener);
}

public void addChangeListener(ChangeListener listener) {
    radio.addChangeListener(listener);
}

public Icon getImage() {
    return image.getIcon();
}

public void setImage(Icon icon) {
    image.setIcon(icon);
}

} // end class RadioButtonWithImage