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.
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.
Creating a Window
GUI components such as windows and labels are, in fact, objects. JFrame is a class and the GUI component window can be created by using a JFrame object. Various attributes are associated with a window. For example:
- Every window has a title.
- Every window has width and height.
The class JFrame provides various methods to control the attributes of a window. The methods provided by the class JFrame are:
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)
Teaching Tip
|
Descriptions of these methods can be found in Table 6-1 in the text. A more detailed description of JFrame’s methods can be found at:
|
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.
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.
Teaching Tip
|
Chapter 11 discusses the principles of inheritance in detail. Constructors are covered in detail in Chapter 8.
|
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.
Getting Access to the Content Pane
The class JFrame has the method getContentPane that can be used to access the content pane of the window. However, the class JFrame does not have the necessary tools to manage the components of the content pane. 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:
public void add(Object obj)
public void setLayout(Object obj)
The method setLayout is used to set the layout of the content pane. To set the layout of the container to a grid, you use the class GridLayout. Consider the following statement:
pane.setLayout(new GridLayout(5, 2));
This statement creates an object belonging to the class GridLayout and assigns that object as the layout of the content pane, pane, by invoking the setLayout method.
If you do not specify a layout, Java uses a default layout. If you specify a layout, you must set the layout before adding any components.
Teaching Tip
|
Java provides many layout managers. A tutorial on layout managers for Java can be found at:
|
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. Some of the constructors for JLabels are:
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.
JTextField
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:
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)
JButton
To create a button, Java provides the class JButton and the following methods:
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.
Teaching Tip
|
Components such as JButton, JTextField, and JLabel are part of Java’s Swing framework. A tutorial on creating GUI interfaces with Swing can be found at:
|
Handling an Event
When you click a JButton an event is created, known as an action event, which sends a message to another object, known as an action listener. When the listener receives the message, it performs some action. Sending a message or an event to a listener object simply means that some method in the listener object is invoked with the event as the argument. This invocation happens automatically; you will not see the code corresponding to the method invocation. However, you must specify two things:
- For each JButton, you must specify the corresponding listener object. In Java, this is known as registering the listener.
- You must define the methods that will be invoked when the event is sent to the listener. Normally, you will write these methods and you will never write the code for invocation.
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.
Teaching Tip
|
Tutorials regarding how to write various types of listeners, including ActionListeners, can be found at:
|
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
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, you need to 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.
Teaching Tip
|
More information on Object-Oriented Design can be found at:
|
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.
Primitive Data Types and the Wrapper Classes
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:
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()
As of J2SE 5.0, Java has simplified the wrapping and unwrapping of primitive type values, called the autoboxing and auto-unboxing of primitive types. An example of autoboxing is as follows:
int x;
Integer num;
num = 25;
The third statement is equivalent to the statement
Num = new Integer( 25 );
This is an example of autoboxing.
An example of auto-unboxing is:
x = num;
This is equivalent to the statement
x = num.intValue();
Teaching Tip
|
More information on autoboxing can be found at:
|
Teaching Tip
|
A listing of all of the wrapper classes in the java.lang package can be found at:
|
class IntClass
The class IntClass is similar to the class Integer, but is not immutable. The class DoubleClass is identical to IntClass, except that it deals with double values instead of int values.
Java Workshop Manila
Java Workshop Manila