Lab05 Press Your Luck

Objective: Random numbers.

When do Value and Total change?  When does High Score change?  How many labels do you need?  How many buttons? When you click the button, what happens? 

The game is played when you click the button. A random number from 1 to 11 is generated. If the number is 3 or more, the number is added to the total. If the number is 2 or less the total is reset to 0. High Score is the highest total reached so far in the game.

This lab is organized with a driver, a panel, and a display. The display holds the three labels.  The panel holds the display and the button.  Locate these elements at the right.
Text Box:  7 public class Panel05 extends JPanel   8 {   9  private Display05 display;  10  public Panel05()  11   {  12    setLayout(new FlowLayout());  13        14    display = new Display05();  15    add(display);  16         17    JButton button = new JButton('Press Your Luck');  18    button.addActionListener(new Listener());  19    add(button);  20  }  21  private class Listener implements ActionListener  22  {  23   public void actionPerformed(ActionEvent e)  24    {  25        26    }  27  }  28 }
How is panel designed?  Notice that Line 9 declares a reference that is empty at this point.

The concrete display object is instantiated in Line 14 and added to the panel in Line 15, exactly as the odometer was instantiated and added in the Odometer lab. 

If we want to see the code for a display object, we have to go to the Display05Luck class and look.

Lines 17-25 code the typical steps to create a working button. 

INSTRUCTIONS: Complete the implementation of the Display05Luck class.  Update picks a random number from 1 to 11.  If the number is 1 or 2 then your score goes to zero.  Otherwise, add the current value to your running total.  Lastly, if there is a new high score, update it.

Filename (load).  Complete the Listener. What should the button do? 
Filename (load). 


  1. Add a reset label that displays how many times a 2 or less was generated.
  2. Add a Start Again button that sets value, total, number of resets, and high score back to 0
  3. Like the Odometer, each label is a different foreground/background color