This Java program combines a GUI and the Coin object we studied in Chapter 5. Wr
ID: 3680580 • Letter: T
Question
This Java program combines a GUI and the Coin object we studied in Chapter 5. 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 called "Heads", and a JTextField that contains the number of times the coin is Heads.
a JLabel called "Tails", and a JTextField that contains the number of times the coin is Tails.
a JButton called "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.
Explanation / Answer
Hi,
Added comments too for easy understanding.
CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CoinFlipping extends JApplet implements ActionListener {
//these are labels for head and tail.
JLabel lHeads, lTails;
JTextField outputH, outputT;
JButton b;
// counters for heads and tails
int heads = 0;
int tails = 0;
//init method for the logic execution.
public void init( ) {
Container c = getContentPane( );
c.setLayout( new FlowLayout( ) );
lHeads = new JLabel( "Number of heads" );
outputH = new JTextField( 10 );
outputH.setEditable( false );
c.add( lHeads );
c.add( outputH );
lTails = new JLabel( "Number of tails" );
outputT = new JTextField( 10 );
outputT.setEditable( false );
c.add( lTails );
c.add( outputT );
b = new JButton( "FLIP" );
b.addActionListener( this );
c.add( b );
}
//this is for action performed.
public void actionPerformed( ActionEvent e ) {
//this is to toss a coin.
boolean toss = flip_con( );
if ( toss )
outputH.setText( "" + ++heads );
else
outputT.setText( "" + ++tails );
}
//this is flip_con implementation.
boolean flip_con( ) {
int rn = ( int ) ( Math.random( ) * 2 );
if ( rn == 0 )
return false;
else
return true;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.