I have a group of RadioButton
s in a JPanel
. I want them to have a green background when not selected, and a red background when one is selected. By the very nature of JRadioButton
s, only one should be red at a single time.
My problem is that setting the background in an ActionListener
does not work since it doesn't update the remaining buttons.
Is there any way I can iterate over elements of the ButtonGroup
? (The method getElements
doesn't seem to be what I need.)
Here is an SsCcE:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(1024, 768));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = new JPanel();
// This is the important stuff. :)
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < 5; i++) {
final JRadioButton btn = new JRadioButton(String.valueOf(i));
group.add(btn);
content.add(btn);
btn.setBackground(Color.green);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (btn.isSelected()) {
btn.setBackground(Color.red);
} else {
btn.setBackground(Color.green);
}
}
});
}
// The important stuff is over. :(
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}