Unit Three – User Interface
July 2011
Developed by Shane Torbert
edited by Marion Billington
under the direction of Gerry Berry
Thomas Jefferson High School for Science and Technology
Fairfax County Public Schools
Fairfax, Virginia
FCPS
Java
Packets
http://www.tjhsst.edu/
Three-1
Java
Unit3
Contributing Authors
The author is grateful for additional contributions from Michael Auerbach, Marion Billington, Charles Brewer, Margie
Cross, Cathy Eagen, Anne Little, John Mitchell, John Myers, Steve Rose, Ankur Shah, John Totten, and Greg W.
Price.
The students' supporting web site can be found at http://academics.tjhsst.edu/compsci/
The teacher's (free) FCPS Computer Science CD is available from Stephen Rose (srose@fcps.edu)
License Information
This work is licensed under the Creative Commons Attribution-Noncommercial-No Derivative Works 2.5 License. To
view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/2.5/ or send a letter to Creative
Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
You are free:
* to Share -- to copy, distribute, display, and perform the work
Under the following conditions:
* Attribution. You must attribute the work in the manner specified by the author or licensor.
* Noncommercial. You may not use this work for commercial purposes.
* No Derivative Works. You may not alter, transform, or build upon this work.
* For any reuse or distribution, you must make clear to others the license terms of this work.
* Any of these conditions can be waived if you get permission from the copyright holder, smtorbert@fcps.edu
You are free to alter and distribute these materials within your educational institution provided that appropriate credit
is given and that the nature of your changes is clearly indicated. As stipulated above, you may not distribute altered
versions of these materials to any other institution. If you have any questions about this agreement please e-mail
smtorbert@fcps.edu
http://academics.tjhsst.edu/compsci/
http://creativecommons.org/licenses/by-nc-nd/2.5/
Three-2
Java Unit3
Java Instruction Plan—Unit Three
Section One – Event Driven Programming Page
Lab00: Hello Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-3 to 5
Lab01: Hello Text Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-6 to 8
Lab02: Multiple Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-9 to 11
Lab03: Hailstone Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-12 to 14
Section Two – What’s Inside the Black Box?
Lab04: Odometer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-15 to 16
Lab05: Press Your Luck . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-17 to 19
Lab06: Luck of the Roll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-20 to 21
Lab07: GCD and LCM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-22 to 24
Section Three – GUI Formatting
Lab08: Sum of a Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-25 to 26
Lab09: Subway Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-27 to 29
Lab10: High - Low . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-29 to 30
Lab11: Last Stone Wins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-31
Section Four – I/O Window Output
Lab12: Asterisks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-32 to 34
Lab13: The Necklace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-35
Lab14: Bowling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-36
Section Five – Additional GUI Topics
Lab15: More GUI Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-37
Lab16: The jGrasp Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-39
Lab17: Mixing Graphics and GUIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Three-40
Three-3
Java
Unit3
Discussion Panels, GUI Components, and Listeners
A Graphical User Interface (GUI) allows users to point and click on on-screen "buttons." Almost all
computers today are operated through GUIs, but once upon a time people used keyboards, punchcards, or even
dials and toggle switches. A GUI is quite hard to program, unless you are in an object-oriented language, in
which case it is fairly easy. That's because an object oriented language takes advantage of abstraction,
inheritance, and encapsulation. For example, each object in a GUI, such as the buttons, textfields, labels,
panels, and frame, "knows" its own attributes and methods—that is encapsulation. Like the Polkadot and Ball
classes in Unit 2, each GUI object even knows how to draw itself. Each object inherits some of its methods
from higher up the hierarchy, overrides some methods, and adds new methods. The hierarchy proceeds from
abstract to concrete, with the programmers assigning powers at the appropriate level. For example, abstractly
considered, all JComponent objects can be assigned ActionListeners. You, the programmer, work with the
concrete objects when you assign a specific button to a specific listener. (You did the same thing in Unit 2,
when you assigned a timer to a specific listener.) You also, as the last programmer in the chain, get to say
exactly what happens when each button is clicked.
The structure of the applications in
this unit is exactly the same as in Unit
2. The driver creates a frame, puts the
panel on the frame, and displays the
frame. The panel has the buttons,
labels, text boxes, and even other
panels. Visually, a GUI is not a whole
lot different from straight graphics.
However, in a GUI the program reacts
to something the user does. Unlike
programs in Units 1 and 2, our GUI
will wait patiently until a button is
clicked, then it springs forth and does
its thing. Best of all, we don't have to
know the details of how all that
works. Someone else programmed
buttons and listeners for us.
Just for fun, here is the hierarchy, including interfaces, for a JButton:
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.AbstractButton
javax.swing.JButton
All Implemented Interfaces:
Accessible, ImageObserver, ItemSelectable, MenuContainer, Serializable, SwingConstants
listener
component
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Component.html
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Container.html
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComponent.html
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/AbstractButton.html
http://java.sun.com/j2se/1.4.2/docs/api/javax/accessibility/Accessible.html
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/image/ImageObserver.html
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/ItemSelectable.html
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/MenuContainer.html
http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/SwingConstants.html
Three-4
Java Unit3
Lab00 Hello Button
Objective
Understand frames, panels, and GUI components.
Background
The drivers in Unit 3 are exactly the same as those in Unit 2. The panel
will have GUI components like this:
Specification
Filenames Unit3\Lab00\Driver00.java and Unit3\Lab00\Panel00.java. Enter the source code for the driver.
Enter the source code for the resource class (the panel) as shown below, then compile and run the program.
Lines 4-6: import the swing,
awt, and event classes.
Line 9: The panel's JLabel is
a private field. This is
essential if we want to access
the label in the listener.
Lines 10-22: The constructor.
Line 12: set the panel‘s layout
Lines 14-17: Instantiate a
label, set its font and color,
then add it to the panel.
Lines 19-21: Instantiate a
button, register its listener,
then add it to the panel.
Line 23: Listener implements
the ActionListener interface,
meaning that actionPerformed
must have code.
Line 28: (" " + x) converts a
number to a string, because
setText requires a string.
The scope of a variable is the region of the program in which it is valid to use that variable. The global
private JLabel label in Line 9 has a wider scope than the local JButton button on Line 19 and the
local double x in Line 27. The blue lines down the side in jGrasp show the scope of the different variables.
We need to declare the panel‘s private Jlabel label on Line 9 because we want the listener on Line
28 to use it. In contrast, the listener does not need to use the button. Therefore, we declared JButton
button on Line 19, restricting its scope entirely inside the constructor. Similarly, the double x in Line 27
has a scope that entirely inside the actionPerformed method, which is where we want to use it.
Test Data Go to www.tjhsst.edu/compsci
JLabel
JButton
4 import javax.swing.*;
5 import java.awt.*;
6 import java.awt.event.*;
7 public class Panel00 extends JPanel
8 {
9 private JLabel label; //a private field
10 public Panel00()
11 {
12 setLayout(new FlowLayout());
13
14 label = new JLabel("0.0000000000000000");
15 label.setFont(new Font("Serif", Font.BOLD, 20));
16 label.setForeground(Color.blue);
17 add(label);
18
19 JButton button = new JButton("Random"); //local
20 button.addActionListener(new Listener());
21 add(button);
22 }
23 private class Listener implements ActionListener
24 {
25 public void actionPerformed(ActionEvent e)
26 {
27 double x = Math.random(); //local variable
28 label.setText("" + x);
29 }
30 }
31 }
http://www.tjhsst.edu/compsci
Three-5
Java
Unit3
Exercises Lab00
1) What three steps do you have to do to create buttons?
2) add(label) adds a label to the _______________.
3) There are at least four GUI components showing below. Label them all.
4) A fifth GUI component is hidden, but you know it is there. What is it?
5) What do you have to do to program the action of a button?
6) What interface does every button‘s listener implement? ____________________________
7) What method is in that interface? _________________________________
8) ―To implement an interface‖ means to write concrete methods for all the ___________________ methods in the interface.
9) Give the range of values that the following will generate:
a. Math.random(); ____________________
b. Math.random() * 10; _____________________
c. Math.random() * 100; _______________________
d. Math.random() * 6; ______________________
Three-6
Java Unit3
Discussion GUI components, strings, numbers
The initial text that appears in any label, button, or text box can be specified through the object's constructor.
private JLabel label;
private JTextField box;
public Panel01()
{
label = new JLabel("0.0");
JButton button = new JButton("SQRT");
box = new JTextField("0.0", 10);
In the last command, the text field named "box" will display 0.0, right justified, and it will be 10 characters in
total width. There is no way to set the font or color for all components with a single command. You must call
the set methods on each component individually. Look at the API for all the relevant formatting commands.
To a Java compiler, "6" is different from 6, which is different from 6.0. "6" is a string, 6 is an integer, and 6.0
is a double, and each representation of 6 is stored in a completely different way. We humans want to convert
each kind of 6 into the other kinds. In Lab01, we will want to retrieve a number from the text field. We use
the method getText, which returns a string. Then we turn that string (the ―6‖) into a double (the 6.0) using
the Double.parseDouble method.
double d = Double.parseDouble(box.getText());
After we do the arithmetic with d, often saving the result in a new double variable, then we need to display
the result on the screen. In other words, we have to change the double into a string. We can do so with
label.setText("" + d);
In Java, the quote-quote-plus returns the string representation of the double. Then setText accepts the
string and displays it on the label.
There is a difference between a declaration and an instantiation. In a declaration, such as,
private JLabel label;
you create a reference that eventually will point to an object. In a declaration you don‘t create the object itself.
A call to the class‘s constructor, using the keyword new, actually instantiates the object. Only then does the
JLabel reference point to the JLabel object.
label = new JLabel("");
label OBJECT
We declare and instantiate in separate steps whenever we need to access the private reference in several
methods, i.e. when the scope of the field must be global. We saw this in Lab00 at lines 9, 14, and 28.
label
Three-7
Java
Unit3
Lab01 Hello Text Box
Objective
Fields vs. local variables
Background
Lines 9-10: These three
declarations create private
fields because the fields need
to be accessed later in the
listener.
Line 13: FlowLayout is the
simplest GUI layout. The first
component added to the panel
is placed at the center top.
Additional components are
placed to the right, or on the
next line. Be sure to drag the
corner of the frame and watch
how the flow works.
Line 15-31. Notice the
different components are
instantiated, formatted, and
added to the panel.
Components appear in the
order in which they are added.
Line 19: This button is
declared local because it does
not need to be accessed in the
listener, unlike the label and
the textField.
Specification
Filename Unit3\Lab01\Driver01.java. Create an appropriate driver. Make sure to add a panel object of type
Panel01.
Filename Unit3\Lab01\Panel01.java. Type in the resource class above. Implement the method
actionPerformed to find square roots. What happens if you type a negative number into the text box?
Extension
Edit your program to handle negative numbers correctly, i.e., returns 5i. You will need an if-
statement.
Warning! A common error is to write Line 15 as JTextField box = new JTextField("0.0", 10);
Write Line 15 with this mistake. Compile and run. Explain the error message.
Test Data
Go to www.tjhsst.edu/compsci.
25
4 import javax.swing.*;
5 import java.awt.*;
6 import java.awt.event.*;
7 public class Panel01 extends JPanel
8 {
9 private JLabel label1; //field
10 private JTextField box; //field
11 public Panel01()
12 {
13 setLayout(new FlowLayout());
14
15 box = new JTextField("0.0", 10);
16 box.setHorizontalAlignment(SwingConstants.RIGHT);
17 add(box);
18
19 JButton button = new JButton("SQRT"); //local
20 button.addActionListener(new Listener());
21 add(button);
22
23 label1 = new JLabel("0.0");
24 label1.setFont(new Font("Serif", Font.BOLD, 20));
25 label1.setForeground(Color.blue);
26 add(label1);
27 }
28 private class Listener implements ActionListener
29 {
30 public void actionPerformed(ActionEvent e)
31 {
32 //get the number
33 //take the square root
34 //display it
35 }
36 }
37 }
http://www.tjhsst.edu/compsci
Three-8
Java Unit3
Exercises Lab01
1) There are at least five GUI components showing below. Label them all.
2) Describe a ―string‖ in Computer Science.
3) Describe a ―double‖ in Computer Science.
4) How do you get a string that is in a textField?
5) How do you change that string into a double?
6) How do you change a double into a string, as when you setText a numerical answer into a label?
7) Define and/or explain every underlined term.: double d = Double.parseDouble( textField.getText() );
Complete this scavenger hunt using Sun’s on-line Java API.
8) What is the lowest common ancestor of JButton, JLabel, and JTextField? _______________________
9) How many methods does the ActionListener interface specify? _________________________
10) What package is ActionEvent in? _________________________
11) How many classes extend JButton? __________________
12) How many constructors does JButton define? _________________________
13) How many methods does JButton define? _________________________
14) JButton has a setText method. When would you ever want to use a button's setText in the middle of
a program?
15) How many constructors does JTextField define? _________________________
16) Write the code to instantiate a JTextField with "Enter name" in the field, and the field is 20 spaces wide.
Three-9
Java
Unit3
import
public class Panel02 extends JPanel
{
//fields--for objects that must be accessed later
public Panel02() //constructor
{
format the panel,
instantiate and format the GUI components,
register the listeners,
add the GUI components.
}
private class Listener1 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
. . .
}
}
//another listener
//another listener
}
Discussion Multiple Buttons
The event model we have seen thus far can be applied to any number of buttons and listeners.
listener1 listener2
component1 component2
listener3
component3
Simply declare a separate listener class for each different action that has to be performed. Register listener
objects with buttons appropriately.
button1.addActionListener(new Listener1());
button2.addActionListener(new Listener2());
button3.addActionListener(new Listener3());
The code above will work, but the names are not informative. You should use informative names, such as:
randomNumber.addActionListener(new RandomListener());
reciprocalButton.addActionListener(new ReciprocalListener());
quitButton.addActionListener(new QuitListener());
As the code below says, each private listener class implements the ActionListener interface. That interface
specifies exactly one abstract method, actionPerformed. That means that each Listener code must define
its own actionPerformed method to specify what happens on each button-click.
Be careful! The placement of
braces is critical to ensure the
proper scope of the fields and
listeners. The listener classes
must be able to access the
fields. In other words, the
scope of the private fields must
include the listener classes.
Also, each of the listener classes
must be visible outside the
constructor. Do not define one
listener class inside another or
the one inside will not be visible
from the constructor.
Sadly, a common error is to put
the definition of one listener
class entirely inside the
definition of another.
Three-10
Java Unit3
Lab02 Multiple Buttons
Objective
GUIs and listeners.
Background
When working with numbers and text, remember that the argument passed to the setText method must be a
string.
Similarly, remember that the return type passed out of the setText method is always a string. If you want
to do arithmetic on the return type, you'll need to parse it, either to an int or to a double.
Some static (class) methods in the Math class that you should know:
Math function Example command
Absolute value x = Math.abs(y);
Square root x = Math.sqrt(y);
Square x = y * y;
Cube root x = Math.pow(y, 1.0/3.0);
Set x equal to 1 x = Math.pow(y, 1/3); //due to integer division, 1/3 0
Raise to a power x = Math.pow(2, 10); //Recall that 2 10
= 1024
Sine, y in degrees x = Math.sin(y * Math.PI / 180.0);
Cosine, y in degrees x = Math.cos(Math.toRadians(y));
Specification
Filename Unit3\Lab02\Driver02.java. Create an appropriate driver. Make sure to add a panel object of type
Panel02. Size recommendations for the frame are included as part of the on-line demo.
Filename Unit3\Lab02\Panel02.java. Reverse engineer the panel based on the on-line demo. Notice that there
is no text box, but that there is only one label. Since you have four buttons, you will have to have four
listeners. To make the Quit button work, check the System class in Sun‘s Java API for some hints.
Test Data
Go to www.tjhsst.edu/compsci.
http://www.tjhsst.edu/compsci
Three-11
Java
Unit3
Exercises Lab02
1) label.setText(number)gives an error message. What is the error, and how do you fix it?
2) How do you change a string into a double?
3) Define and/or explain every underlined item.
private class Handler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int num = Integer.parseInt( text.getText() );
int result = num * num;
label2.setText ("The square of the number is " + result);
}
}
Vocabulary practice:
3a) In the code above, ActionListener is a(n) __________________
3b) In the code above, actionPerformed is a(n) __________________
3c) In the code above, Integer is a(n) __________________
3d) In the code above, parseInt is a(n) __________________
3e) In the code above, text is a(n) __________________
3f) In the code above, getText is a(n) __________________
3g) In the code above, int is a(n) __________________
3h) In the code above, result is a(n) __________________
3i) In the code above, label2 is a(n) __________________
3j) In the code above, setText is a(n) __________________
Three-12
Java Unit3
Discussion Primitive Data Types
A data type defines a specific kind of data, e.g., numbers, Strings, or Robots, and how a computer internally
stores and manipulates that data. A class, either imported or user-defined, defines some specific data type.
Java also provides several primitive data types including int (for integers) and double (for decimal
numbers). Primitive data types do not contain any methods. Useful integer methods are instead defined in a
wrapper class. The integer wrapper class is called Integer and the decimal wrapper class is called Double.
Thus, we have Integer.parseInt and Double.parseDouble. Other useful methods are in the API.
Internally, objects are accessed by references, but primitives store their data directly. The convention in Java
is that names of classes start with a capital letter and names of primitives are lower case, reserved words.
Robot karel = new Robot(); Turtle smidge = new Turtle(); int x = 5; double d = 5.00;
karel smidge x 5 d 500 2
Robot is a class, Turtle is a class, primitive type: int primitive type: double
karel is a pointer smidge is a pointer x stores 5 d stores 5.00
One tricky part about ints and doubles is casting, which means changing the data type from one to the
other. Sometimes Java casts automatically and sometimes you must cast explicitly. Suppose your code is:
int x = 4; //creates room for an integer, calls it "x", and stores 4 in it.
double y = 0; //creates room for a double, calls it "y", and stores 0.0 in it.
...
y = (double)x; //it works: the code casts 4 explicitly, which becomes 4.0 and is stored in y.
y = x; //it works: the integer 4 is promoted to 4.0 automatically.
However,
x = y; //illegal, due to loss of precision. The 0.0 does not become 0 automatically.
x = (int)y; //it works: you must explicitly tell the computer to truncate the decimal.
Presumably, the Java creators decided that 4 can become 4.0 without risk, but that decimals shouldn't lose their
decimal parts without the programmer explicitly saying that it is okay.
If you copy and paste code too much you may accidentally apply parseInt or parseDouble when you
need the other one. Always look at the type of the variable and choose appropriately.
int x = Integer.parseInt(“5”);
double y = Double.parseDouble(“5.0”);
Don‘t forget how to change numbers into strings: label.setText(“” + number);
Java is a strongly typed language, meaning that Java is very particular about requiring the correct data type,
either int, double, String, or some other object. A large part of the compiler‘s job is to guarantee
type-safe code. Other, uncompiled, languages do not care so much about type-safe code.
Three-13
Java
Unit3
Lab03 Hailstone Numbers
Objective
Integer division and modulus.
Background Here‘s the Hailstone algorithm: start with a random integer from 1 to 100. If the number is even, divide it by
two to generate the next number. If the number is odd, multiply it by three and add one to generate the next
number. Keep generating in that way. What happens? The answer is the hailstone numbers, which you will
see in action once your Lab03 is working.
This is new for you: in Java, when you divide two integers you will always get an integer quotient! The
remainder, if any, is ignored and thrown away. For example:
int x = (10 * 6 + 7 – 30) / 8;
Sometimes, finding the remainder is quite useful. The remainder is calculated by the modulus operator,
whose symbol in Java is %. For instance:
int y = (10 * 6 + 7 – 30) % 8;
To understand integer division and modulus, think back to long division. For example, 37 8
Notice that the / does not round up. Any remainder is truncated. Truncated means discarded. So even if you
took 9,999/10,000 it would equal zero.
The Hailstone algorithm requires you to determine if an integer is even. A good way to do this is to check to
see if the remainder (%) obtained from dividing the integer by two equals zero. For example: number % 2 == 0
Specification Filename Unit3\Lab03\Driver03.java. Create an appropriate
driver. Make sure to add a panel object of type Panel03. Size
recommendations for the frame are included as part of the on-
line demo.
Filename Unit3\Lab03\Panel03.java (load). Complete the
definition of each listener‘s actionPerformed to reverse
engineer the on-line demo.
Test Data
Be sure to play with the on-line demo that is at
www.tjhsst.edu/compsci.
Extension for math geniuses: Every sequence of Hailstone numbers seems to end in 4, 2, 1, but no one has
proved it to be so. If you come up with a proof, your name will be honored among mathematicians.
x 4
y 5
4
8 37
32
5__
37 / 8 4
37 % 8 5
http://www.tjhsst.edu/compsci
Three-14
Java Unit3
Exercises Lab03
1) Practice integer division, modulus division, and decimal division. Remember the order of operations.
14 / 5
14 % 5 14.0 / 5.0 3 + 19 % 6 – 4
15 / 5
15 % 5 15.0 / 5 1 + 8 % 2
16 / 5
16 % 5 16 / 5.0 2 / 3 * 3
17 / 5
17 % 5 17 / 5. 1234 % 10 / 1
3 / 5
3 % 5 3 / 5. 1234 % 100 / 10
0 / 5 0 % 5 0.0 / 5 1234 % 1000 / 100
2) int amount = Integer.parseInt (―143‖); amount int quarters = amount / 25; quarters amount = amount % 25; int dimes = amount / 10; dimes amount = amount % 10; int nickels = amount / 5; nickels int pennies = amount % 5; pennies int numCoins = quarters + dimes + nickels + pennies; numCoins
3) Given totalSeconds, the total number of seconds, write assignment statements to store the number of
minutes and the number of extra seconds. For example, if totalSeconds = 121, then min = 2 and sec = 1.
4) Write an assignment statement to store the remainder when an integer is divided by 3.
5) Write the code for: if some number x is odd, set a label to print ―odd‖.
6) int x = Double.parseDouble(box.getText()); generates an error. What is it, and how
do you fix it?
Complete this scavenger hunt using Sun’s on-line Java API.
7) What class does the Integer class extend? _________________________
8) What kind of argument does the method parseInt require in the version that requires only a single
argument? _________________________
9) What kind of value does the method parseInt return? _________________________
10) What is the second field listed in the Double class? _________________________
Three-15
Java
Unit3
Discussion The Black Box
Most of us have no idea how buttons and listeners actually work. They are like a black box to us, in that their
private data and their implementation code are hidden and encapsulated. The client, often another
programmer, uses black box objects without knowing how they are doing what they are doing. Furthermore,
we don't care how they work! (If you really want to know how buttons and listeners work, ask your teacher
how to view Sun‘s Java source code.)
In Lab04, you get a chance to do your own black box programming. Driver04 looks exactly like all the other
drivers. It hasa Panel04, which has already been written and compiled for you, but is shown below. Do not
type it in!
Lines 4-6: Import some
mysterious classes.
Line 9: declares a private field
of type Odometer.
Lines 14-15: The panel
instantiates and adds an
odometer object to itself. What
is an odometer object? The
panel doesn‘t know!
Lines 17 – 19: create a button,
as usual.
Line 25: When the button is
clicked, the update method in
the odomoter object is called.
What is update? At this
point, we don't know. All we
know is that it is a method in the
odometer class.
Your job, should you decide to accept it, will be to program the Odometer class.
Draw the CSD scope lines in the code above. Give an example of a global variable: ___________ Give an
example of a local variable: ________________
Fill in the UML diagram for Lab04:
hasa
s
isa
4 import javax.swing.*;
5 import java.awt.*;
6 import java.awt.event.*;
7 public class Panel04 extends JPanel
8 {
9 private Odometer odometer;
10 public Panel04()
11 {
12 setLayout(new FlowLayout());
13
14 odometer = new Odometer();
15 add(odometer);
16
17 JButton button = new JButton("Step");
18 button.addActionListener(new Listener());
19 add(button);
20 }
21 private class Listener implements ActionListener
22 {
23 public void actionPerformed(ActionEvent e)
24 {
25 odometer.update();
26 }
27 }
28 }
JFrame
isa
Three-16
Java Unit3
Lab04 Odometer
Objective
Look inside a black box. Modulus and Integer Division ( % and / )
Background
The shell for the Odometer class is shown below.
An odometer is an object
that displays numbers.
Clearly, the Odometer class
should extend the JPanel
class. Since Odometer isa
JPanel, set the layout. Set
the background to black. Add the GUI components to
make the odometer panel look like an odometer.
Which kind of components do you need? How many?
Default labels are ―clear‖. There is a way to make the