Swing, like most GUI frameworks is event driven, that is, something happens and then you respond to it. You don't known when or in what order those events might occur.
Instead, you use "listeners" (aka a Observer Pattern) to register interest with your components, which tell you when something happens and you take appropriate action based on the current state of your program
Take a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.WEST;
add(new JLabel("Is a banna:"), gbc);
ButtonGroup bg = new ButtonGroup();
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
System.out.println("You guessed " + cmd);
if ("Yellow".equalsIgnoreCase(cmd)) {
JOptionPane.showMessageDialog(TestPane.this, cmd + " is the answer");
} else {
JOptionPane.showMessageDialog(TestPane.this, cmd + " is not the answer");
}
}
};
add(createGuess("Red", listener, bg), gbc);
add(createGuess("Green", listener, bg), gbc);
add(createGuess("Blue", listener, bg), gbc);
add(createGuess("Yellow", listener, bg), gbc);
}
protected JRadioButton createGuess(String guess, ActionListener listener, ButtonGroup bg) {
JRadioButton btn = new JRadioButton(guess);
btn.addActionListener(listener);
bg.add(btn);
return btn;
}
}
}