Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JRadioButton: how to replace text by IconImage?

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

like image 761
Jason Rogers Avatar asked Jul 21 '11 11:07

Jason Rogers


2 Answers

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
like image 196
Eva Avatar answered Sep 20 '22 15:09

Eva


public JRadioButton(String text, Icon icon) and simple example here

like image 38
mKorbel Avatar answered Sep 20 '22 15:09

mKorbel