import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
import javax.swing.border.Border;
public class ASelectedButton {
public static void main(String args[]) {
JFrame frame = new JFrame("Radio Buttons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Options");
panel.setBorder(border);
final ButtonGroup group = new ButtonGroup();
AbstractButton abstract1 = new JRadioButton("One");
panel.add(abstract1);
group.add(abstract1);
AbstractButton abstract2 = new JRadioButton("Two");
panel.add(abstract2);
group.add(abstract2);
AbstractButton abstract3 = new JRadioButton("Three");
panel.add(abstract3);
group.add(abstract3);
AbstractButton abstract4 = new JRadioButton("Four");
panel.add(abstract4);
group.add(abstract4);
AbstractButton abstract5 = new JRadioButton("Five");
panel.add(abstract5);
group.add(abstract5);
ActionListener aListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
Enumeration elements = group.getElements();
while (elements.hasMoreElements()) {
AbstractButton button = (AbstractButton) elements
.nextElement();
if (button.isSelected()) {
System.out.println("The winner is: " + button.getText());
break;
}
}
group.setSelected(null, true);
}
};
JToggleButton button = new JToggleButton("Show Selected");
button.addActionListener(aListener);
Container container = frame.getContentPane();
container.add(panel, BorderLayout.CENTER);
container.add(button, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
|