Unit Three – GUIs & I/O

July 2015

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

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

The teacher's (free) FCPS Computer Science CD is available from Stephen Rose ()

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 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,

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

Java Instruction Plan—Unit Three

Section One – GUI 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 23
Section Three – GUI Formatting
Lab08: Sum of a Series ...... / Three-24 to 25
Lab09: Subway Tokens ...... / Three-26 to 27
Lab10: High - Low ...... / Three-28 to 29
Lab11: Last Stone Wins ...... / Three-30
Section Four – I/O Window Output
Lab12: Asterisks ...... / Three-31 to 33
Lab13: The Necklace ...... / Three-34
Lab14: Bowling ...... / Three-35
Section Five – Additional GUI Topics
Lab15: More GUI Components ...... / Three-36
Lab16: The jGrasp Debugger ...... / Three-38
Lab17: Mixing Graphics and GUIs ...... / Three-39

Discussion

Panels, GUI Components, and Listeners

A Graphical User Interface (a GUI, pronounced “gooey”)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 youassigna 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.

/ / listener
component

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

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

Create 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.

Lines10-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 scopeof a variable is the region of the program in which it is valid to use that variable. The globalJLabel label in Line 9 has a wider scope than the localJButton button on Line 19 and the localdouble 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 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 the only place where we want to use it.

Sample Run Unit3Lab00.jar

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:

  1. Math.random(); ______
  1. Math.random() * 10; ______
  1. Math.random() * 100; ______
  1. Math.random() * 6; ______

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 textField named "box" will display 0.0, be right justified, and be 10 characters wide.

Each GUI component has formatting commands which must be called individually. There is no way to format all your components using one command. The API lists the formatting commands for each kind of component.

Notice the arrows above. In these labs, we often take two steps to create a reference to an object. First, in the private fields of the class, we declare a reference without an object:

label

private JLabel label;

Later, in the constructor, we will point that reference to the object that we instantiate. As always, we instantiate an object by calling the class's constructor, including the keyword new, like this:

label / / OBJECT

label = new JLabel("");

We declare and instantiate in separate steps whenever we need to access the private field's 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.

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 textField. 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() );

So now we have stored the string from the textField as a double value in d. Usually in these labs, we then do some sort of arithmetic with d, often saving the result in a new double variable. The third step is to display the result on the screen. We use setText to display the result, but first we must change the number-value back into a string. We can display our numerical result on a label with the command

label.setText(""+ d);

The quote-quote-plus is a Java shortcut that returns the string representation of the double. Then setText accepts the string and sets it on the label.

Lab01

Hello Text Box

Objective

Fields vs. local variables

Background

Lines 9-10: These two 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-26. 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 locally because it does not need to be accessed in the listener, unlike the label in Line 9 and the textField in Line 10.

Specification

Create Unit3\Lab01\Driver01.java. Create an appropriate driver. Make sure to add a panel object of type Panel01.

Open 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 23 as JLabel label = new JLabel("0.0"); Write Line 23 with this mistake. Compile and run. Explain what null pointer exception means.

Sample Run

Unit3Lab01.jar

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.:

doubled = Double.parseDouble( textField.getText() );

Complete this scavenger hunt using the current on-line Java API. (In jGrasp, go to Help|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 inherits 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.

Discussion

Multiple Buttons

The GUI model we have seen thus far can be applied to any number of buttons and listeners.

/ listener1 / / / listener2
button1 / button2
/ / listener3
button3

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 classimplements the ActionListener interface. That interface specifies exactly one abstract method, actionPerformed. That means thateach Listener code mustdefine its own actionPerformed methodto 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 to the compiler. Do not define one listener class inside another or the one inside will not be foundby the compiler.

Sadly, a common error is to put the definition of one listener class entirely inside the definition of another.

Lab02

Multiple Buttons

Objective

GUIs and listeners.

Background

Remember that GUI labels and textFields always display Strings, even though they may look like numbers to you. When you getText from a label, you will be getting a String. If you want to do arithmetic on that String, you will need to parse it, to convert it either to an int or a double.

Going the other way, when you setText a number to a label, you must first convert the number into its string representation. In Java, we do that with ""+

Some static (class) methodsin 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; or x = Math.pow(y, 2);
Cube root / x = Math.pow(y, 1.0/3.0);
Set x equal to1 / x = Math.pow(y, 1/3); //due to integer division, 1/3  0
Raise to a power / x = Math.pow(2, 10); //Recall that 210 = 1024
Sine, y in degrees / x = Math.sin(y * Math.PI / 180.0);
Cosine, y in degrees / x = Math.cos(Math.toRadians(y));

Specification

Create 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.

Create Unit3\Lab02\Panel02.java. Reverse engineer the panel based on the on-line demo. Notice that there is no text box; there is only one label. Your code must get the value from the label, do an operation, then put the value back on the label. Since you have four buttons, you will have to have four listeners. To make the Quit button work, check the System class in the current Java API for some hints.

Sample Run

Unit3Lab02.jar

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.

privateclassHandlerimplementsActionListener

{

publicvoidactionPerformed(ActionEvent e)

{

intnum = Integer.parseInt( text.getText() );

intresult = num * num;

label2.setText ("The square of the number is " + result);

}

}

Vocabulary practice:

3a) In the code above, ActionListeneris a(n) ______

3b) In the code above, actionPerformedis a(n) ______

3c) In the code above, Integeris a(n) ______

3d) In the code above, parseIntis a(n) ______

3e) In the code above, textis a(n) ______

3f) In the code above, getTextis a(n) ______

3g) In the code above, intis a(n) ______

3h) In the code above, resultis a(n) ______

3i) In the code above, label2is a(n) ______

3j) In the code above, setTextis a(n) ______

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.

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 referencesmidge is a reference x stores 5 d stores 5.00