Download Chapter 6

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 6
Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Chapter Overview
In this chapter, students will learn about basic GUI components in Java, with emphasis on
the components JFrame, JLabel, JTextfield and JButton. They will also learn the general
approach to solving problems using OOD through the use of several examples.
Chapter Objectives
In this chapter, students will:
·
·
·
·
·
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
Graphical User Interface (GUI) Components
Input and output dialog boxes can be used to input data into a program and show the
output of a program. The methods showInputDialog and showMessageDialog found in
the class JOptionPane of package javax.swing could be used to perform this task. These
methods however have only displayed one dialog box at a time. A program that will
display all input and output in one dialog box is called a Graphical User Interface (GUI).
With a GUI, a user can see inputs and outputs simultaneously, as well as change input
values to recalculate output values.
from OHP p2
In a Java GUI, the areas used to get input and show results are called JTextFields. The
labels for these text fields are called JLabels, the buttons that calculate output or close the
GUI are called JButtons, and the window containing all these components is called JFrame.
**
The GUI components are places in an area called the content pane of the window. When a
button in the content pane is clicked an event has occurred. The Java system is very prompt
in listening for the events generated by a program and then reacting to those events.
JFrame is a class and the GUI component window can be created by using a JFrame object.
Every window has a title, a width and a height. The methods provided by the class
JFrame are:
from OHP p7 & 8
public JFrame()
public JFrame(String s)
public void setSize(int w, int h)
public void setTitle(String s)
public void setVisible(Boolean b)
public void setDefaultCloseOperation(int operation)
public void addWindowListener(WindowEvent e)
1.One way to create a window you can declare an object of the type JFrame, instantiate the
object, and then use the various methods listed above to manipulate the window. In this
case, the object created can use the various applicable methods of the class.2. Another way
is to create the class containing the application program by extending the definition of the
class JFrame; to build the class containing the application program “on top of” the class
JFrame, utilizes the mechanism of inheritance. Inheritance means that a new class can be
derived from or based on an already existing class.
When using inheritance, the class containing your application program has more than one
method. In addition to the method main, it has at least one other method that will be used to
create a window object containing the required GUI components (labels, text fields, etc).
This additional method is called a constructor; it is a method of a class that is automatically
executed when an object of the class is created. Typically, it is used to initialize an object
and its name is always the same as the name of the class. Because inheritance is an
important concept in programming languages such as Java, we the second way of creating a
window is described in detail in this chapter. The definition of the class JFrame is extended
by using the modifier and reserved word extends. The class JFrame is contained in the
package javax.swing. An important property of inheritance is that the class
(subclass) —that extends the definition of an existing class—called a superclass—inherits
all the properties of the superclass. The methods setTitle, setSize, setVisible, and
setDefaultCloseOperation are methods of the class JFrame, and these methods can be
inherited by its subclasses.
The class JFrame has the method getContentPane that can be used to access the content
pane of the window. The components of the content pane are managed by declaring a
reference variable of the Container type and then using the method getContentPane. This
can be done as follows:
Container pane = getContentPane();
The class Container is in the package java.awt.
Some methods of the class are:
from OHP p11
public void add(Object obj)
public void setLayout(Object obj)
To create labels, you instantiate objects of the type JLabel. The class JLabel is also
contained in the package javax.swing. There are various attributes associated with a label.
Every label has a title, width, and a height. The class JLabel contains various methods to
control the display of labels. They are:
from OHP p13 & 14
public JLabel(String str)
public JLabel(String str, int align)
public JLabel(String t, Icon icon, int align)
public JLabel(Icon icon)
Labels are then added to the content pane using the add method.
Text fields are objects belonging to the class JTextField. Therefore, you can create a text
field by declaring a reference variable of the type JTextField followed by an instantiation of
the object. Some methods of the class JTextField are:
from OHP p16
public JTextField(int columns)
public JTextField(String str)
public JTextField(String str, int columns)
public void setLayout(String str)
public String getText()
public void setEditable(Boolean b)
public void addActionListener(ActionListener obj)
To create a button, Java provides the class JButton and the following methods:
from OHP p18
public JButton(Icon ic)
public JButton(String str)
public JButton(String str, Icon ic)
public void setText(String str)
public String getText()
public void setEditable(Boolean b)
public void addActionListener(ActionListener obj)
The add method can then be used to add buttons to the content pane.
**
An action event is created when a JButton is clicked; it sends a message to another object
(the action listener). The listener receives the message, and performs some action. Sending
an event to a listener object means that some method in the listener object is invoked with
the event as the argument. This invocation happens automatically; however, you must
specify the corresponding listener object, known as registering the listener and define the
methods that will be invoked when the event is sent to the listener.
Java provides various classes to handle different kinds of events. The action event is
handled by the class ActionListener. The class ActionListener contains the method
actionPerformed, which includes the code the system is to execute when an action event is
generated. The class ActionListener that handles the action event is a special type of class
called an interface. An interface contains only the methods headings; each methods
heading is terminated with a semicolon.
Because the method actionPerformed does not contain a body, you cannot instantiate an
object of the type ActionListener. One way to register an action listener with an object is
to create a class on top of ActionListener so that the required object can be instantiated. The
class created must provide the necessary code for the method actionPerformed. The
interface ActionListener is contained in the package java.awt.event.
Programming Example: Temperature Conversion
This program creates a GUI to convert temperature from Fahrenheit to Centigrade and from
Centigrade to Fahrenheit.
The input to this program is the temperature in Fahrenheit or Centigrade.
The output is the temperature in Centigrade if the input is Fahrenheit, and the temperature
in Fahrenheit if the input is Centigrade.
The solution consists of creating the appropriate JLabels, JTextFields, JButtons, adding
them to the created content pane and calculating the appropriate calculations when the
buttons are clicked and an event is triggered.
from Book P290-298
//Java program to convert temperature between Centigrade and
//Fahrenheit.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class TempConversion extends JFrame
{
private JLabel centigradeLabel;
private JLabel fahrenheitLabel;
private JTextField centigradeTF;
private JTextField fahrenheitTF;
private CentHandler centigradeHandler;
private FahrHandler fahrenheitHandler;
private static final int WIDTH = 500;
private static final int HEIGHT = 50;
private static final double FTOC = 5.0/9.0;
private static final double CTOF = 9.0/5.0;
private static final int OFFSET = 32;
public TempConversion()
{
setTitle("Temperature Conversion");
Container c = getContentPane();
c.setLayout(new GridLayout(1,4));
centigradeLabel = new JLabel("Temp in Centigrade: ",
SwingConstants.RIGHT);
fahrenheitLabel = new JLabel("Temp in Fahrenheit: ",
SwingConstants.RIGHT);
centigradeTF = new JTextField(7);
fahrenheitTF = new JTextField(7);
c.add(centigradeLabel);
c.add(centigradeTF);
c.add(fahrenheitLabel);
c.add(fahrenheitTF);
centigradeHandler = new CentHandler();
fahrenheitHandler = new FahrHandler();
centigradeTF.addActionListener(centigradeHandler);
fahrenheitTF.addActionListener(fahrenheitHandler);
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private class CentHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double centigrade, fahrenheit;
DecimalFormat twoDigits = new DecimalFormat("0.00");
centigrade =
Double.parseDouble(centigradeTF.getText());
fahrenheit = centigrade * CTOF + OFFSET;
fahrenheitTF.setText(""+ twoDigits.format(fahrenheit));
}
}
private class FahrHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double centigrade, fahrenheit;
DecimalFormat twoDigits = new DecimalFormat("0.00");
fahrenheit =
Double.parseDouble(fahrenheitTF.getText());
centigrade = (fahrenheit - OFFSET) * FTOC;
centigradeTF.setText(""+ twoDigits.format(centigrade));
}
}
public static void main( String[] args)
{
TempConversion tempConv = new TempConversion();
}
}
result:
Quick Quiz
1. True or False:
Answer: True
The method setTitle is part of the class JFrame.
2. GUI components are placed in an area of the GUI window called the ____.
Answer: content pane
3.
When a button in the GUI is click a(n) ____ has occurred.
Answer: event
4. True or False: The class Container is part of the package javax.swing.
Answer: False
5. A subclass inherits all the properties of the ____.
Answer: superclass
Object-Oriented Design
The aim of OOD is to build software from components called classes so that if someone
wants to use a class, all they need to know is the various methods provided by that class.
An object combines data and operations on that data in a single unit, a feature called
encapsulation. In OOD, the object is identified first, then the relevant data is identified,
and finally the operations needed to manipulate the object are identified.
A simplified OOD methodology can be expressed in the following steps:
1. Write down a detailed description of the problem.
2. Identify all (relevant) nouns and verbs.
3. From the list of nouns, select objects. Identify data components of each object.
4. From the list of verbs, select the operations.
In order to create objects you first need to create classes; to know what type of classes to
create, and know what an object stores and what operations are needed to manipulate an
object’s data. Because an object consists of data and operations on data in a single unit, in
Java we use the mechanism of classes to combine data and its operations in a single unit. In
OOD methodology, classes, data members of classes (known as fields), and operations are
identified.
from OHP p23, 24 25 26
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 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.
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.
Implementing Classes and Operations
Once the relevant classes, data members of each class, and relevant operations for each
class are identified, the next step is to implement these things in Java. In Java, to
implement operations we write algorithms. Since there is usually more than one operation
on an object, each algorithm is implemented with the help of Java’s methods. However,
Java does not provide all the methods that you will ever need. Therefore, to learn how to
design and implement classes, you first must learn how to construct and implement your
own methods.
Java provides the classes Integer, Double, Character, Long, and Float so that values of
primitive data types can be treated as objects. These classes are called wrappers. They wrap
primitive type values. However, these classes have limitations that have to be followed.
You can create objects of the type, Integer, to store int values, but you cannot change the
value stored in the objects. Parameter passing is a fundamental concept in any
programming language. Therefore, we have created the classes IntClass and DoubleClass,
which are similar to the classes Integer and Double, respectively. You can create objects of
the type IntClass and/or DoubleClass, store, and/or change values of the objects. The data
members and methods in this class are:
from OHP p28 29
data member: int x;
public IntClass()
public IntClass(int num)
public void setNum(int num)
public int getNum()
public void addToNum(int num)
public void multiplyToNum(int num)
public int compareTo(int num)
public Boolean equals(int num)
public String toString()
Quick Quiz
1. The classes Integer, Double, Character, Long, and Float are called ____ because they
wrap primitive type values.
Answer: wrappers
2.
True or False: Methods of a class are identified with the help of verbs appearing in the
problem specification.
Answer: True
3. True or False: Encapsulation is the ability of objects to combine data and operations
on that data in a single unit.
Answer: True
4.
In order to create objects you first need to create ____.
Answer: classes
5. In object-oriented design if someone wants to use a class, all he/she needs to know are
the ____ provided by that class.
Answer: methods
Discussion Questions
Some interesting topics of discussion in Chapter Six include:
Ø
Ø
Ø
Discuss different situations where a GUI would be especially useful.
Discuss examples of OOD.
Discuss real world examples of OOD
Projects to Assign
1.
Assign odd Exercises.
2.
Assign Programming Exercises 1 and 5.
Key Terms
Ø
Ø
Class: a collection of data members and methods associated with those data members
Constructor: method of a class that is automatically executed when an object of the
class is created; used to initialize an object
Ø GUI: Graphical User Interface
Ø Inheritance: property that allows for a new class to be derived from or based on an
already existing class
Ø Pixel: smallest unit of space on your screen that you can write
Ø Subclass: class that extends the definition of an existing class and inherits all its
properties
Ø Superclass: existing class extended by another class