Chapter 5: Conditionals and Loops (3)

Lab Exercises

 

Topics                                                 Lab Exercises

 

Determining Event Sources                                Vote Counter, Revisited

 

Dialog Boxes                                                         Modifying EvenOdd.java

                                                                                A Pay Check Program

 

Checkboxes & Radio Buttons                            Adding Buttons to StyleOptions.java

 

 


Vote Counter, Revisited

 

Chapter 4 had a lab exercise that created a GUI with two buttons representing two candidates (Joe and Sam) in an election or popularity contest. The program computed the number of times each button was pressed. In that exercise two different listeners were used, one for each button. This exercise is a slight modification. Only one listener will be used and its ActionPerformed method will determine which button was pressed.

 

The files VoteCounter.java and VoteCounterPanel.java contain slight revisions to the skeleton programs used in the Chapter 4 exercise. Save them to your directory and do the following:

 

  1. Add variables for Sam - a vote counter, a button, and a label.

 

  1. Add the button and label for Sam to the panel; add the listener to the button.

 

  1. Modify the ActionPerformed method of the VoteButtonListener class to determine which button was pressed and update the correct counter. (See the LeftRight example or the Quote example for how to determine the source of an event.)

 

  1. Test your program.

 

  1. Now modify the program to add a message indicating who is winning. To do this you need to instantiate a new label, add it to the panel, and add an if statement in actionPerformed that determines who is winning (also test for ties) and sets the text of the label with the appropriate message.

 

 

 

 

 

 

//*********************************************************

// VoteCounter.java
//
// Demonstrates a graphical user interface and event
// listeners to tally votes for two candidates, Joe and Sam.
//*********************************************************
import javax.swing.JFrame;
 
public class VoteCounter
{
    //----------------------------------------------
    // Creates the main program frame.
    //----------------------------------------------
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Vote Counter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        frame.getContentPane().add(new VoteCounterPanel());
        
        frame.pack();
        frame.setVisible(true);
    }
}
 

 

//*********************************************************
// VoteCounterPanel.java  
//
// Panel for the GUI that tallies votes for two candidates,
// Joe and Sam.
//*********************************************************
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class VoteCounterPanel extends JPanel
{
    private int votesForJoe;
    private JButton joe;
    private JLabel labelJoe;
 
    //----------------------------------------------
    // Constructor: Sets up the GUI.
    //----------------------------------------------
    public VoteCounterPanel()
    {
        votesForJoe = 0;
 
        joe = new JButton("Vote for Joe");
        joe.addActionListener(new VoteButtonListener());
 
        labelJoe = new JLabel("Votes for Joe: " + votesForJoe);
 
        add(joe);
        add(labelJoe);
 
        setPreferredSize(new Dimension(300, 40));
        setBackground(Color.cyan);
    }
 
    //***************************************************
    // Represents a listener for button push (action) events
    //***************************************************
    private class VoteButtonListener implements ActionListener
    {
        //----------------------------------------------
        // Updates the appropriate vote counter when a 
        // button is pushed for one of the candidates.
        //----------------------------------------------
        public void actionPerformed(ActionEvent event)
        {
            votesForJoe++;
            labelJoe.setText("Votes for Joe: " + votesForJoe);
        }
    }
}
 
 

Modifying EvenOdd.java

 

File EvenOdd.java contains the dialog box example in Listing 5.21 the text.

 

  1. Compile and run the program to see how it works.
  2. Write a similar class named SquareRoots (you may modify EvenOdd) that computes and displays the square root of the integer entered.

 

 

//********************************************************************

//  EvenOdd.java       Author: Lewis/Loftus

//

//  Demonstrates the use of the JOptionPane class.

//********************************************************************

 

import javax.swing.JOptionPane;

 

class EvenOdd

{

   //-----------------------------------------------------------------

   //  Determines if the value input by the user is even or odd.

   //  Uses multiple dialog boxes for user interaction.

   //-----------------------------------------------------------------

   public static void main (String[] args)

   {

      String numStr, result;

      int num, again;

 

      do

      {

         numStr = JOptionPane.showInputDialog ("Enter an integer: ");

 

         num = Integer.parseInt(numStr);

 

         result = "That number is " + ((num%2 == 0) ? "even" : "odd");

 

         JOptionPane.showMessageDialog (null, result);

 

         again = JOptionPane.showConfirmDialog (null, "Do Another?");

      }

      while (again == JOptionPane.YES_OPTION);

   }

}


A Pay Check Program

 

Write a class PayCheck that uses dialog boxes to compute the total gross pay of an hourly wage worker. The program should use input dialog boxes to get the number of hours worked and the hourly pay rate from the user. The program should use a message dialog to display the total gross pay. The pay calculation should assume the worker earns time and a half for overtime (for hours over 40).

 


Adding Buttons to StyleOptions.java

 

The files StyleOptions.java and StyleOptionsPanel.java are from Listings 5.22 and 5.23 of the text (with a couple of slight changes—an instance variable fontSize is used rather than the literal 36 for font size and the variable style is an instance variable rather than local to the itemStateChanged method). The program demonstrates checkboxes and ItemListeners. In this exercise you will add a set of three radio buttons to let the user choose among three font sizes. The method of adding the radio buttons will be very similar to that in the QuoteOptionsPanel class (Listing 5.25 of the text). Before modifying the program compile and run the current version to see how it works and study the QuoteOptionsPanel example.

 

Do the following to add the radio buttons to the panel:

 

1.     Declare three objects small, medium, and large of type JRadioButton.

 

2.     Instantiate the button objects labeling them "Small Font," "Medium Font," "Large Font." Initialize the large font button to true. Set the background color of the buttons to cyan.

 

3.     Instantiate a button group object and add the buttons to it.

 

4.     Radio buttons produce action events so you need an ActionListener to listen for radio button clicks.  The code you need to add to actionPerformed will be similar to that in the QuoteListener in Listing 5.25. In this case you need to set the fontSize variable (use 12 for small, 24 for medium, and 36 for large) in the if statement, then call the setFont method to set the font for the saying object.   (Note: Instead of adding an ActionListener you could use the current ItemListener and add code to check to see if the source of the event was a radio button.)

 

5.     In StyleOptionsPanel() add the ItemListener object to each button and add each button to the panel.

 

6.     Compile and run the program. Note that as the font size changes the checkboxes and buttons re-arrange themselves in the panel. You will learn how to control layout later in the course.

 

 

//********************************************************************

//  StyleOptions.java       Author: Lewis/Loftus

//

//  Demonstrates the use of check boxes.

//********************************************************************

 

import javax.swing.JFrame;

 

public class StyleOptions

{

   //-----------------------------------------------------------------

   //  Creates and presents the program frame.

   //-----------------------------------------------------------------

   public static void main (String[] args)

   {

      JFrame frame = new JFrame ("Style Options");

      frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

 

      StyleOptionsPanel panel = new StyleOptionsPanel();

      frame.getContentPane().add (panel);

 

      frame.pack();

      frame.setVisible(true);

   }

}


//********************************************************************

//  StyleOptionsPanel.java       Author: Lewis/Loftus

//

//  Demonstrates the use of check boxes.

//********************************************************************

 

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

 

public class StyleOptionsPanel extends JPanel

{

    private int fontSize = 36;

    private int style = Font.PLAIN;

    private JLabel saying;

    private JCheckBox bold, italic;

 

    //-----------------------------------------------------------------

    //  Sets up a panel with a label and some check boxes that

    //  control the style of the label's font.

    //-----------------------------------------------------------------

    public StyleOptionsPanel()

    {

      saying = new JLabel ("Say it with style!");

      saying.setFont (new Font ("Helvetica", style, fontSize));

 

      bold = new JCheckBox ("Bold");

      bold.setBackground (Color.cyan);

      italic = new JCheckBox ("Italic");

      italic.setBackground (Color.cyan);

     

      StyleListener listener = new StyleListener();

      bold.addItemListener (listener);

      italic.addItemListener (listener);

 

      add (saying);

      add (bold);

      add (italic);

 

setBackground (Color.cyan);

      setPreferredSize (new Dimension(300, 100));

    }

 

   //*****************************************************************

   //  Represents the listener for both check boxes.

   //*****************************************************************

   private class StyleListener implements ItemListener

   {

      //--------------------------------------------------------------

      //  Updates the style of the label font style.

      //--------------------------------------------------------------

      public void itemStateChanged (ItemEvent event)

      {

        style = Font.PLAIN;

       

        if (bold.isSelected())

            style = Font.BOLD;

       

        if (italic.isSelected())

            style += Font.ITALIC;

       

        saying.setFont (new Font ("Helvetica", style, fontSize));

      }

   }

}