Description
Keywords
Objectives
Author / jsa
Organisation
Version / Version x
Date / August 2010
Copyright
Unit 11Object-oriented programming: Graphical user interface
Please ensure that you enter a name in the yellow box above that will be used as a banner title across the top of your web pages.
The following Item is used by the Resource Converter, Please do not delete it.
The first page of your online resource should begin below this line
Introduction
Most of the content in this unit is based on chapter 12 in Liang. The objectives of this unit are:
•GUI components
–To distinguish simple GUI components.
–To create user interfaces using frames, panels, and some simple UI components
•Layout managers
–To understand the role of layout managers
–To use the FlowLayout, GridLayout, and BorderLayout managers to layout components in a container
•Graphics
–To specify colors using the Color class
–To paint graphics using the paintComponent method on a panel
–To draw strings, lines, rectangles and ovals using the drawing methods in the Graphics class
Getting started with GUI
A Graphical User Interface (GUI) presents a number of graphical elements to the user to interact with the program. See the diagram below. Typical GUI components include windows, menus, buttons and text areas. Java provides many predefined classes for building GUI applications. These classes are provided in two packages called: Abstract Windows Toolkit (AWT) and Swing. In Java, to write a GUI program, we derive new classes from those provided in AWT or Swing.
The overall structure of AWT and Swing can be classified as
- Graphics;
- Components;
- Layout managers;
- Event handlers;
- Image manipulation.
Graphics deals with drawing of shapes and lines; selecting of fonts, colour and so on. Components are items such as buttons, text fields, menus and scroll bars. We can put them in containers and then choose a layout manager to arrange them suitably on screen. The sub-package java.awt.event handles events, such as pressing buttons and moving mouse, through event handlers and listeners.
When Java was introduced, the GUI classes were bundled in AWT. With the release of Java 2, a set of similar components are introduced in Swing. Swing components are more platform independent than AWT components. To distinguish new Swing components from their AWT counterparts, the names of Swing components begin with a prefixed J.
The principles of GUI design and event-handling are the same for AWT and Swing.
Creating a frame
One way to create a graphical user interface is to create a frame. Frame can be used as the basis to contain other user interface components in Java GUI applications.
We now look at how a frame can be created.
import javax.swing.*;
public class MyFrame1 extends JFrame{
MyFrame1(String title) {
setTitle(title);
setSize(400,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
MyFrame1 frame = new MyFrame1("MyFrame");
}
}
The above program creates a frame by extending the Swing class JFrame which is in the package javax.swing. In the constructor of MyFrame1, we invoke a number of set methods, such as setTitle(…) and setSize(…). These methods are defined in the classes above MyFrame1 in the class hierarchy. The frame is not displayed until setVisible(true) is applied. When you run the MyFrame1 program, a window will be displayed.
Student activity 11.1:
Implement and run the above program.
Adding components to a frame
Let’s now add some components to the frame. Every frame has a content pane. See the diagram below. A content pane is automatically created when a JFrame object is created. A JFrame object uses the content pane to hold components in the frame.
To add a JButton to the ContentPane, we can use the following statements:
Container contentPane = getContentPane();
//obtain the content pane of the frame
JButton ok = new JButton("first_ok_button");
//create a button object
contentPane.add(ok);
// add the ok button to the content pane
We can revise MyFrame1 to add a button to the frame as shown below:
import javax.swing.*;
import java.awt.Container;
public class MyFrame2 extends JFrame{
MyFrame2(String title) {
setTitle(title);
setSize(400,300);
Container contentPane = getContentPane();
JButton ok = new JButton("first_ok_button");
contentPane.add(ok);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
MyFrame2 frame = new MyFrame2("MyFrame");
}
}
Note that getContentPane returns a Container which is provided in AWT rather than Swing. Therefore we need to import java.awt.Container.
Student activity 11.2:
Implement and run MyFrame2.
Let’s now use the following example to illustrate how to change the background colour of a JFrame and its content pane. Suppose we want the background of the frame to be blue. Let’s try to do this by using this statement setBackground(Color.BLUE); as shown in the program below.
public class MyFrame_color extends JFrame{
MyFrame_color(String title) {
setTitle(title);
setSize(400,300);
setBackground(Color.BLUE);//sets the frame bg color
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
MyFrame_color frame = new MyFrame_color("MyFrame");
}
}
Student activity 11.3:
Implement and run the MyFrame_color example.
Can you explain why the background colour of the frame does not appear to be blue?
From the above activity, you should have noticed that although the program has the statement setBackground(Color.BLUE);, the background colour does not appear to be blue unless when you are resizing the frame. This is because the frame’s content pane is “on top” of the frame. Let’s now change the program. Instead of setting the background colour of the frame, we set the background colour of the content pane as shown below; i.e. we replace the setBackground(Color.BLUE) statement by the getContentPane().setBackground(Color.BLUE)statement.
public class MyFrame_color extends JFrame{
MyFrame_color(String title) {
setTitle(title);
setSize(400,300);
getContentPane().setBackground(Color.BLUE);
//sets the contenpane bg color
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
MyFrame_color frame = new MyFrame_color("MyFrame");
}
}
Some GUI components
We now have a look of some more components: JButton, JTextField and JLabel.
The Component class is the root for all GUI components and containers, i.e.
- Component is the superclass of Container
- Container is the superclass of JComponent
- JComponent is the superclass of AbstractButton
- AbstractButton is the superclass of JButton
- JComponent is the superclass of JTextComponent
- JTextComponent is the superclass of JTextField
- JTextComponent is the superclass of JTextArea
- JComponent is the superclass of JLabel
The Component class provides methods such as setting and getting background colours. The Container class provides methods for adding component to the container; setting layout manager; and painting the component.
A JButton has a number of constructors. The mostly used constructor is
JButton(String text)
In the program MyFrame2 above, we have seen how the ok button is created.
JButton ok = new JButton("first_ok_button");
A JTextField is an input area where the user can type in characters. Text fields are useful in that they enable the user to enter in variable data (such as a name or a description). Commonly used constructors and methods are:
•JTextField(int columns)
Creates an empty text field with the specified number of columns.
•JTextField(String text)
Creates a text field initialized with the specified text.
•getText()
Returns the string from the text field.
•setText(String text)
Puts the given string in the text field.
A JLabel is a display area for a short text. Constructors and methods include the following:
•JLabel()
•JLabel(String text)
•setText(String text)
•getText()
Containers
Some GUI components are called containers because they can contain a number of components, for example, windows, frames and panels. If we need to display a large number of components on the screen, it would be easier to manage if we can put these components into a number of (sub-)containers. The ContentPane is an example of a container. It is a subclass of the Container class. We can use the add method to put components in a container. For example, to add a JButton to the ContentPane, we can use the following the statements:
Container contentPane = getContentPane();
JButton ok = new JButton("first_ok_button");
contentPane.add(ok);
We now introduce another container component: JPanel. JPanel is a subclass of JComponent. JPanel can be used as container or sub-containers for grouping user interface components. It is recommended that you place the user interface components in panels and place the panels in a frame. You can also place panels in a panel. The following fragments of code illustrate how you can create an instance of a JPanel and add a JButton to it.Often programmers use a JPanel instead of the content pane when adding components to a frame as JPanel is a subclass of JComponent; therefore it provides more methods than the ContentPane. The following fragment of code illustrates that after creating a JPanel called myContentPane, we add myContentPane to the content pane of the frame. We can then work with myContentPane by adding components to it.
Container contentPane= getContentPane();
JPanel myContentPane= new JPanel();
contentPane.add(myContentPane);
JButton ok = new JButton("first_ok_button");
myContentPane.add(ok);
Student activity 11.4:
Modify MyFrame2 by using a JPanel and adding more GUI components to it.
Layout Manger
The GUI components are placed in containers. Each container has a layout manager to control how the GUI components within the container can be arranged. Layout managers are set in containers using the setLayout(LayoutManager) method in a container. Java provides a number of predefined layout managers. Here we will cover the following three layout managers:
•FlowLayout
•GridLayout
•BorderLayout
Flow Layout
FlowLayout is the simplest layout manager. The components are arranged in the container from left to right in the order in which they were added. When one row becomes filled, a new row is started.
The class ShowFlowLayout below illustrates how a FlowLayout manager is used.
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.Container;
import java.awt.FlowLayout;
public class ShowFlowLayout extends JFrame {
public ShowFlowLayout() {
// Get the content pane of the frame
Container container = getContentPane();
container.setLayout(new FlowLayout(FlowLayout.LEFT));
// Add buttons to the frame
for (int i = 1; i <= 10; i++)
container.add(new JButton("Component " + i));
}
/** Main method */
public static void main(String[] args) {
ShowFlowLayout frame = new ShowFlowLayout();
frame.setTitle("ShowFlowLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setVisible(true);
}
}
Here is an example of its output.
In the above program, we have set the layout manager to be FlowLayout using this statement:
container.setLayout(new FlowLayout(FlowLayout.LEFT));
The parameter FlowLayout.LEFT indicates that the components will be placed from left to right.
Student activity 11.5:
Implement and run the ShowFlowLayout program.
Explore the effect of the layout by resizing the frame.
Explore the effect of the layout by changing the above statement to the following:
container.setLayout(new FlowLayout(FlowLayout.RIGHT));
Explore the effect of the layout by changing the above statement to:
container.setLayout(new FlowLayout());
Grid Layout
The GridLayout manager arranges components in a grid (matrix) formation with the number of rows and columns defined by the constructor. The components are placed in the grid from left to right starting with the first row, then the second, and so on.
The following program illustrates how to use a GridLayout.
import javax.swing.*;
import java.awt.*;
public class ShowGridLayout extends JFrame {
public ShowGridLayout() {
// Get the content pane of the frame
Container container = getContentPane();
// Set GridLayout,three rows and two columns
container.setLayout(new GridLayout(3,2));
// Add labels and text fields to the frame
container.add(new JLabel("First Name"));
container.add(new JTextField(8));
container.add(new JLabel("MI"));
container.add(new JTextField(1));
container.add(new JLabel("Last Name"));
container.add(new JTextField(8));
}
/** Main method */
public static void main(String[] args) {
……
}
}
Here is an output.
The above fragment of code shows that we have set the layout manager for the content pane to be grid layout with three rows and two columns. Some labels, e.g.”First Name”, and some text fields are added to the content pane.
The basic rules for specifying the number of rows and the number of columns are
- The number of rows or the number of columns can be zero, but not both. If one is zero and the other is nonzero, the nonzero dimension is fixed, while the zero dimension is determined dynamically by the layout manager.
- If both the number of rows and the number of columns are nonzero, the number of rows is the dominating parameter; that is, the number of rows is fixed, and the layout manager dynamically calculates the number of columns.
Student activity 11.6:
Implement and run the ShowGridLayout program.
Modify the program by changing the layout manager to FlowLayout to see the effect on the layout of the different components.
Border Layout
The BorderLayout manager divides the container into five areas: East, South, West, North, and Center. The Borderlayout is the default layout manager for JFrame.
To add a component to a particular area, we use the add(Component, constraint) method, where constraint is
BorderLayout.EAST,
BorderLayout.SOUTH,
BorderLayout.WEST,
BorderLayout.NORTH, or
BorderLayout.CENTER
The following fragment of code illustrates the use of a BorderLayout manager.
public class ShowBorderLayout extends JFrame {
public ShowBorderLayout() {
// Get the content pane of the frame
Container container = getContentPane();
// Add buttons to the frame
container.add(new JButton("East"), BorderLayout.EAST);
container.add(new JButton("South"), BorderLayout.SOUTH);
container.add(new JButton("West"), BorderLayout.WEST);
container.add(new JButton("North"), BorderLayout.NORTH);
container.add(new JButton("Center"), BorderLayout.CENTER);
}
……
Here is an output of such a program.
The above fragment of code shows that we have set the layout manager to be BorderLayout. Five buttons are added to the five different areas.
An integrated example
We now show an example that integrates several of the above concepts together. This example requires us to develop a program that would give us the following front view of a microwave oven.
As you can see we need to arrange a lot of components in a frame. To make it easier to manage, we will use panels as sub-containers to group some components together. We will put the 12 buttons (numbers 0 to 9, start and stop) in a panel called p1. We will then group the text area and the panel p1 to another panel p2. We now have just two components to arrange, one big button representing the glass door on the left and the panel p2 on the right as shown in the diagram below.
Student activities 11.7:
Write a java program to implement the oven front view example
Hints
Here is a possible solution:Microwave
The Color class and drawing graphics
In this section we introduce the Color class and how to draw graphics.
The Color Class
You can set colours for GUI components by using the java.awt.Color class. (Note the spelling “color” for the Color class.) There are thirteen standard colours: black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white and yellow. They are defined as constants in java.awt.Color. You can use the following methods to set the component’s background and foreground colours:
setBackground(Color c);
setForeground(Color c);
For example, in the fragment of code below, the ok button is set to be red and the whole content pane is set to be green.
MyFrame(String title) {
… …
Container container = getContentPane();
JButton ok = new JButton("first_ok_button");
container.add(ok);
ok.setBackground(Color.red);// sets the ok button to be red
container.setBackground(Color.green);
// sets the content pane to be green
… …
}
Drawing in Swing
Another important use of JPanel is for drawing. It is recommended that to draw things in a panel rather than directly in a frame.
To draw in a panel, you usually create a new class that extends JPanel and override the paintComponent method to tell the panel how to draw things. You can then display strings; draw geometric shapes; and view images on the panel. The signature of the paintComponent method is
void paintCompnenet(Graphics g)
The Graphics object g is created automatically by the Java Virtual Machine for every visible GUI component. This object controls how information is drawn. You can use various drawing methods defined in the Graphics class to draw strings and shapes. The following are some commonly used methods:
•Drawing lines, e.g.drawLine(50,50,100,60), draws a line from (50,50) to (100,60)
•Drawing rectangles, e.g. drawRect(20,20,100,50), draws a rectangle with (20,20) as the top left corner; 100 is the length and 50 is the width.
•Drawing filled rectangles, e.g. fillRect(20,20,100,50), draws a rectangle as above but filled with the current colour.
•Drawing ovals, e.g. drawOval(30,30,50,50), draws an oval bounded by an invisible rectangle whose top left corner is at (30,30); length is 50 and width is 50.
•Drawing Strings, e.g. drawString(“Hello”, 50,50), draws a string starting from the position (50,50).
•Changing the colour of the graphics object, e.g. setColor(Color.red), sets of colour of the graphics object to be red.
In the class below, we have extended JPanel. The paintComponent method is used to draw two rectangles in the panel.