JAVA Write a GUI program that has a Coin object as one of its instance variables
ID: 3677118 • Letter: J
Question
JAVA
Write a GUI program that has a Coin object as one of its instance variables. When a button is pushed, the Coin is flipped, and its heads/tails result is used to update the GUI. The GUI has the following widgets: a JLabel "Heads", and a JTextField that contains the number of times the coin is Heads. a JLabel "Tails", and a JTextField that contains the number of times the coin is Tails. a JButton "Flip". When the user clicks the Flip button, the coin is flipped one time, and the Heads or Tails JTextField is updated as appropriate. The GUI initially displays 0 as the value for both Heads and Tails.
Thank you!
Explanation / Answer
// CoinFlipping.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CoinFlipping extends Frame implements ActionListener {
// GUI Components
JLabel labelHeads, labelTails;
JTextField outputH, outputT;
JButton b;
// counters for heads and tails
int heads = 0;
int tails = 0;
public void init( ) {
JFrame c = new JFrame("Coin FLip");
c.setLayout(new FlowLayout());
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
labelHeads = new JLabel( "Number of heads" );
outputH = new JTextField( 10 );
outputH.setEditable( false );
outputH.setText("0");
c.add( labelHeads );
c.add( outputH );
labelTails = new JLabel( "Number of tails" );
outputT = new JTextField( 10 );
outputT.setEditable( false );
outputT.setText("0");
c.add( labelTails );
c.add( outputT );
b = new JButton( "FLIP" );
b.addActionListener( this );
c.add( b );
c.setSize(600,200);
c.setVisible(true);
}
public void actionPerformed( ActionEvent e ) {
boolean toss = flip( );
if ( toss )
outputH.setText( "" + ++heads );
else
outputT.setText( "" + ++tails );
}
boolean flip( ) {
int rn = ( int ) ( Math.random( ) * 2 );
if ( rn == 0 )
return false;
else
return true;
}
public static void main(String[] args) {
CoinFlipping coin = new CoinFlipping();
coin.init();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.