Write a GUI program that contains two radio buttons in a radio button group. One
ID: 3535825 • Letter: W
Question
Write a GUI program that contains two radio buttons in a radio button group. One radio button should have the text Heads and the other Tails. There should be a JButton with the text Flip. The Heads radio button should be selected by default. The user should select heads or tails and then click the Filp button. When the Flip button is clicked, the program should generate a random integer 0 or 1 (0 = heads, 1 = tails), and show a JOptionPane Message box indicating whether the user called the flip correctly and won (i.e. heads radio button selected and 0 generated or tails radio button selected and 1 generated) or incorrectly and lostType your question here
Explanation / Answer
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class CoinFlip extends JFrame {
private JButton flip;
private JRadioButton heads;
private JRadioButton tails;
private JPanel radioPanel;
private JPanel flipPanel;
private ButtonGroup buttonGroup;
public CoinFlip() {
buttonGroup = new ButtonGroup();
flip = new JButton("Flip");
flip.addActionListener(new FlipListener());
heads = new JRadioButton("Heads",true);
tails = new JRadioButton("Tails");
buttonGroup.add(heads);
buttonGroup.add(tails);
radioPanel = new JPanel();
radioPanel.add(heads);
radioPanel.add(tails);
flipPanel = new JPanel();
flipPanel.add(flip);
setLayout(new GridLayout(2,1));
add(radioPanel);
add(flipPanel);
setTitle("CoinFlip");
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new CoinFlip();
}
private class FlipListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Random rng_ = new Random();
int headsOrTails = rng_.nextInt(2);
if ((headsOrTails == 0 && heads.isSelected()) || (headsOrTails == 1 && tails.isSelected()))
JOptionPane.showMessageDialog(null,"You win!");
else
JOptionPane.showMessageDialog(null,"Sorry, you lose!");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.