Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Chapter 6:
Graphical User Interface (GUI) and
Object-Oriented Design (OOD)
Java Programming:
Program Design Including Data Structures
Chapter Objectives
Learn about basic GUI components
Explore how the GUI components JFrame, JLabel, JTextField,
and JButton work
Become familiar with the concept of event-driven programming
Discover events and event handlers
Explore object-oriented design
Learn how to identify objects, classes, and members of a class
Java Programming: Program Design Including Data Structures
2
Graphical User Interface (GUI)
Components
View inputs and outputs simultaneously
One graphical window
Input values in any order
Change input values in window
Click buttons to get output
Java Programming: Program Design Including Data Structures
3
Java GUI Components
Java Programming: Program Design Including Data Structures
4
Graphical User Interface (GUI)
Components (continued)
GUI components placed in content pane
GUI components:
Windows
Labels
Text areas
Buttons
Java Programming: Program Design Including Data Structures
5
GUI Components
Added to content pane of window
Not added to window itself
Pixel: A picture element
Java Programming: Program Design Including Data Structures
6
Windows
Can be created using a Frame object
The class Frame provides various methods to
control attributes of a window
Measured in pixels of height and width
Attributes associated with windows:
Title
Width
Height
Java Programming: Program Design Including Data Structures
7
class JFrame
GUI window instance created as instance of Frame
Provides various methods to control window
attributes
Java Programming: Program Design Including Data Structures
8
Methods Provided by the class
JFrame
Java Programming: Program Design Including Data Structures
9
Methods Provided by the class
JFrame (continued)
Java Programming: Program Design Including Data Structures
10
Two Ways to Create a Window
First way:
Declare object of type JFrame
Instantiate object
Use various methods to manipulate window
Second way:
Create class-containing application program by extending
definition of class JFrame
Utilize mechanism of inheritance
Java Programming: Program Design Including Data Structures
11
Content Pane
Inner area of GUI window (below title bar, inside
border)
To access content pane:
Declare reference variable of type Container
Use method getContentPane of class
JFrame
Java Programming: Program Design Including Data Structures
12
Methods Provided by the class
Container
Java Programming: Program Design Including Data Structures
13
class JLabel
Labels: Objects of a particular class type
class JLabel: Used to create labels
Label attributes:
Title
Width
Height
To create a label:
Instantiate object of type JLabel
Modify attributes to control display of labels
Java Programming: Program Design Including Data Structures
14
Methods Provided by the class
JLabel
Java Programming: Program Design Including Data Structures
15
Methods Provided by the class
JLabel (continued)
Java Programming: Program Design Including Data Structures
16
class JTextField
Text fields: Objects belonging to class
JTextField
To create a text field:
Declare reference variable of type JTextField
Instantiate object
Java Programming: Program Design Including Data Structures
17
Methods Provided by the class
JTextField (continued)
Java Programming: Program Design Including Data Structures
18
class JButton
Provided to create buttons in Java
To create a button:
Use the same technique that is used to create
JLabel and JTextField
Java Programming: Program Design Including Data Structures
19
Methods Provided by the class
JButton
Java Programming: Program Design Including Data Structures
20
Methods Provided by the class
JButton (continued)
Java Programming: Program Design Including Data Structures
21
Handling an Event
Action event: created when JButton is clicked
Event listener: An object that receives a message
when JButton is clicked
In Java, you must register the listener
Java Programming: Program Design Including Data Structures
22
Handling an Event (continued)
class ActionListener
Handles action event
Part of package java.awt.Event
The class ActionListener is a special type of
class (interface)
Must contain the actionPerformed method
Java Programming: Program Design Including Data Structures
23
Rectangle Program: Sample Run
Java Programming: Program Design Including Data Structures
24
Rectangle Program: Sample Run
//Given the length and width of a rectangle, this Java
//program determines its area and perimeter.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private JLabel lengthL, widthL,
areaL, perimeterL;
private JTextField lengthTF, widthTF,areaTF, perimeterTF;
private JButton calculateB, exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
Java Programming: Program Design Including Data Structures
25
Rectangle Program: Sample Run
public RectangleProgram()
{
// Create four labels
lengthL = new JLabel("Enter the length: ",
SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ",
SwingConstants.RIGHT);
areaL = new JLabel("Area: ",
SwingConstants.RIGHT);
perimeterL = new JLabel("Perimeter: ",
SwingConstants.RIGHT);
//Create four textfields
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
perimeterTF = new JTextField(10);
Java Programming: Program Design Including Data Structures
26
Rectangle Program: Sample Run
//create Calculate Button
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
//Create Exit Button
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
//Set the title of the window
setTitle("Area and Perimeter of a Rectangle");
//Get the container
Container pane = getContentPane();
//Set the layout (Grid 5 rows 2 cols)
pane.setLayout(new GridLayout(5,2));
Java Programming: Program Design Including Data Structures
27
Rectangle Program: Sample Run
//Place all items created
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(perimeterL);
pane.add(perimeterTF);
pane.add(calculateB);
pane.add(exitB);
//set the size of the window and display it
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Java Programming: Program Design Including Data Structures
28
Rectangle Program: Sample Run
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area, perimeter;
length = Double.parseDouble(lengthTF.getText());
width = Double.parseDouble(widthTF.getText());
area = length * width;
perimeter = 2 * (length + width);
areaTF.setText("" + area);
perimeterTF.setText("" + perimeter);
}
}
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
Java Programming: Program Design Including Data Structures
29
Rectangle Program: Sample Run
public static void main(String[] args)
{
RectangleProgram rectObject = new RectangleProgram();
}
}
Java Programming: Program Design Including Data Structures
30
Programming Example:
Temperature Conversion
Input: Temperature in Fahrenheit or Celsius
Output: Temperature in Celsius if input is
Fahrenheit; temperature in Fahrenheit if input is
Celsius
Java Programming: Program Design Including Data Structures
31
Programming Example:
Temperature Conversion
(continued)
Solution:
1. Create the appropriate JLabels,
JTextFields, JButtons
2. Add them to the created content pane
3. Calculate the appropriate conversions when the
buttons are clicked and an event is triggered
Java Programming: Program Design Including Data Structures
32
Sample Run for TempConversion
Java Programming: Program Design Including Data Structures
33
Sample Run for TempConversion
//Java program to convert temperature between Celsius and
//Fahrenheit.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TempConversion extends JFrame
{
private JLabel celsiusLabel;
private JLabel fahrenheitLabel;
private JTextField celsiusTF;
private JTextField fahrenheitTF;
private CelsHandler celsiusHandler;
private FahrHandler fahrenheitHandler;
private
private
private
private
private
static
static
static
static
static
final
final
final
final
final
int WIDTH = 500;
int HEIGHT = 75;
double FTOC = 5.0 / 9.0;
double CTOF = 9.0 / 5.0;
int OFFSET = 32;
Java Programming: Program Design Including Data Structures
34
Sample Run for TempConversion
//Java program to convert temperature between Celsius and
//Fahrenheit.
public TempConversion()
{
setTitle("Temperature Conversion");
Container c = getContentPane();
c.setLayout(new GridLayout(1, 4));
celsiusLabel = new JLabel("Temp in Celsius: ",
SwingConstants.RIGHT);
fahrenheitLabel = new JLabel("Temp in Fahrenheit: ",
SwingConstants.RIGHT);
celsiusTF = new JTextField(7);
fahrenheitTF = new JTextField(7);
Java Programming: Program Design Including Data Structures
35
Sample Run for TempConversion
c.add(celsiusLabel);
c.add(celsiusTF);
c.add(fahrenheitLabel);
c.add(fahrenheitTF);
celsiusHandler = new CelsHandler();
fahrenheitHandler = new FahrHandler();
celsiusTF.addActionListener(celsiusHandler);
fahrenheitTF.addActionListener(fahrenheitHandler);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
Java Programming: Program Design Including Data Structures
36
Sample Run for TempConversion
private class CelsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double celsius, fahrenheit;
celsius =
Double.parseDouble(celsiusTF.getText());
fahrenheit = celsius * CTOF + OFFSET;
fahrenheitTF.setText(""+ String.format("%.2f", fahrenheit));
}
}
Java Programming: Program Design Including Data Structures
37
Sample Run for TempConversion
private class FahrHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double celsius, fahrenheit;
fahrenheit =
Double.parseDouble(fahrenheitTF.getText());
celsius = (fahrenheit - OFFSET) * FTOC;
celsiusTF.setText(""+ String.format("%.2f", celsius));
}
}
public static void main( String[] args)
{
TempConversion tempConv = new TempConversion();
}
}
Java Programming: Program Design Including Data Structures
38
Object-Oriented Design
Simplified methodology:
1.
2.
3.
4.
5.
Write down detailed description of problem
Identify all (relevant) nouns and verbs
From list of nouns, select objects
Identify data components of each object
From list of verbs, select operations
Java Programming: Program Design Including Data Structures
39
Object-Oriented Design:
Example 1
Problem statement:
Write a program to input the length and width of a
rectangle, and calculate and print the perimeter and
area of the rectangle
Nouns:
Length, width, rectangle, perimeter, area
Java Programming: Program Design Including Data Structures
40
class Rectangle with Data
Members and Operations
Java Programming: Program Design Including Data Structures
41
Object-Oriented Design:
Example 2
A place to buy candy is from a candy machine. A
new candy machine is bought for the gym, but it is
not working properly. The candy machine has four
dispensers to hold and release items sold by the
candy machine and a cash register. The machine
sells four products —candies, chips, gum, and
cookies—each of which is stored in a separate
dispenser. You have been asked to write a program
for this candy machine so that it can be put into
operation.
Java Programming: Program Design Including Data Structures
42
Object-Oriented Design:
Example 2
The program should do the following:
Show the customer the different products sold by the
candy machine
Let the customer make the selection
Show the customer the cost of the item selected
Accept money from the customer
Return change
Release the item, that is, make the sale
Java Programming: Program Design Including Data Structures
43
Object-Oriented Design:
Example 2
Java Programming: Program Design Including Data Structures
44
Object-Oriented Design:
Example 2
Java Programming: Program Design Including Data Structures
45
Implementing Classes
and Operations
Algorithms are used to implement operations
Construct and implement your own methods
Classes Integer, Double, Character, Long,
Float:
Known as wrapper classes
Provided so that values of primitive data types can
be treated as objects
Have limitations (cannot change value stored in
objects)
Java Programming: Program Design Including Data Structures
46
The class Integer
Java Programming: Program Design Including Data Structures
47
The class Integer
(continued)
Java Programming: Program Design Including Data Structures
48
The class Integer
(continued)
Integer num;
num = new Integer(86)
Java Programming: Program Design Including Data Structures
49
The class Integer
(continued)
int x;
Integer num;
num = 25;
This statement is equivalent to the statement:
num = new Integer(25);
The expression:
num = 25;
is referred to as autoboxing of the int type.
Java Programming: Program Design Including Data Structures
50
The class Integer
(continued)
int x;
Integer num;
The statement:
x = num;
This statement is equivalent to the statement:
x = num.intValue();
This statement is referred to as auto unboxing of the int type.
Java Programming: Program Design Including Data Structures
51
The class Integer
(continued)
To compare the values of two Integer objects,
you can use the method compareTo
If you want to compare the values of two Integer
objects only for equality, then you can use the
method equal
Java Programming: Program Design Including Data Structures
52
The class IntClass
Java Programming: Program Design Including Data Structures
53
The class IntClass
(continued)
Java Programming: Program Design Including Data Structures
54
Chapter Summary
Every GUI contains a window
Various components are added to the content pane
of a window
class Frame is used to create windows
JLabel is used to label GUI components and
display information to user
JTextField is used for input/output
JButton generates action event
Action event is sent to action listener
Action listener must have method called
actionPerformed
Java Programming: Program Design Including Data Structures
55
Chapter Summary (continued)
A class is a collection of data members and methods
associated with those members.
Object-oriented design (OOD):
Starts with a problem statement.
Identifies required classes with nouns in problem
statement.
Identifies required methods with verbs in problem
statement.
Java Programming: Program Design Including Data Structures
56