Exemplo de RadioButtons em Java
De Aulas
1import java.awt.BorderLayout;
2import java.awt.GridLayout;
3import java.awt.event.ActionEvent;
4import java.awt.event.ActionListener;
5import javax.swing.BorderFactory;
6import javax.swing.ButtonGroup;
7import javax.swing.JButton;
8import javax.swing.JFrame;
9import javax.swing.JPanel;
10import javax.swing.JRadioButton;
11
12public class Radio {
13 private JFrame janela;
14 private JRadioButton yesButton;
15 private JRadioButton noButton;
16 private JRadioButton maybeButton;
17 private JButton getButton;
18 private ButtonGroup bgroup;
19
20 public Radio () {
21 janela = new JFrame("Teste de Radio Button");
22 janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
23 janela.setLayout(new BorderLayout());
24
25 yesButton = new JRadioButton("Yes", true);
26 noButton = new JRadioButton("No", false);
27 maybeButton = new JRadioButton("Maybe", false);
28
29 bgroup = new ButtonGroup();
30 bgroup.add(yesButton);
31 bgroup.add(noButton);
32 bgroup.add(maybeButton);
33
34 getButton = new JButton("Get");
35 getButton.addActionListener(new ActionListener() {
36 public void actionPerformed(ActionEvent arg0) {
37 String out = "Get";
38 if (yesButton.isSelected()) {
39 out = yesButton.getText();
40 } else if (noButton.isSelected()) {
41 out = noButton.getText();
42 } else if (maybeButton.isSelected()) {
43 out = maybeButton.getText();
44 }
45 getButton.setText(out);
46 }
47 });
48
49 JPanel radioPanel = new JPanel();
50 radioPanel.setLayout(new GridLayout(4, 1));
51 radioPanel.add(yesButton);
52 radioPanel.add(noButton);
53 radioPanel.add(maybeButton);
54 radioPanel.add(getButton);
55
56 radioPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
57 .createEtchedBorder(), "Married?"));
58 janela.add(radioPanel);
59 janela.pack();
60 janela.setVisible(true);
61 }
62
63 public static void main(String [] args) {
64 new Radio();
65 }
66}