Computing II
Tutorial 3
Prepared by: Ng Mee Mee
Outlines
Key Concepts of Unit 4
Introduction
Marking Scheme and TMA3 support
Key Concepts of Unit 4
Explain the problem of creating a cross-
platform graphical user interface
Describe the way of creating GUIs.
Use different GUI components.
Apply different layout managers
Describe the concept of event handling.
Apply event handling in GUIs.
Develop java applets
Introduction
Two sets of packages for building GUIs
AWT (Abstract Window Toolkit)
1st generation of GUI package
Use native window GUI components to construct the GUI, the
appearance of the same GUI-based application varies on
different platform ( refer Unit 4, page 4)
import java.awt.*;
Swing
An improve version of GUI package
Do not rely on the native window to construct the GUI, provide
a consistent appearances across platform. ( refer Unit 4, page
6)
Import javax.swing.*;
3 steps to create a GUI
1. Creating a top-level container object
Example: a standalone window (JFrame)
2. Creating GUI components and adding them
to the top-level container object.
Example: button, label, textfield checkbox
3. Adding the functionalities to the GUI
components.
Example: clicking a button to perform an action
Inheritance Hierarchy of GUI Classes
Java GUI Components
Frames
Frame is a window that is not contained inside
another window. Frame is the basis to contain
other user interface components in Java GUI
applications.
The Frame class can be used to create
windows.
For Swing GUI programs, use JFrame class to
create widows.
Methods Provided by the class
JFrame
Methods Provided by the class
JFrame
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.
Sample
Code
First way: TestJFrame1.java
import javax.swing.*;
public class TestJFrame1 {
public static void main(String[] args) {
JFrame frame = new JFrame("Test Frame");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Sample
Code
Second way:
TestJFrame2.java
import javax.swing.*;
public class TestJFrame2 extends JFrame {
public TestJFrame2(){
super("Test Frame");
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
TestJFrame2 frame = new TestJFrame2();
}
}
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. Title bar
Content pane
Methods Provided by the
class Container
class JButton
Provided to create buttons in Java.
To create a button:
JButton btnOk = new JButton(“OK”);
Methods Provided by the class
JButton
Methods Provided by the class
JButton
Sample
Code
FrameWithButton.java
import javax.swing.*;
import java.awt.*;
public class FrameWithButton extends JFrame {
private JButton btnOK;
public FrameWithButton(){
super("Test Frame");
btnOK = new JButton("OK");
Container pane =getContentPane();
pane.add(btnOK);
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
FrameWithButton frame = new FrameWithButton();
}
}
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.
Methods Provided by the class
JLabel
Methods Provided by the class
JLabel
class JTextField
Text fields: Objects belonging to class
JTextField.
To create a text field:
Declare reference variable of type JTextField.
Instantiate object.
Methods Provided by the class JTextField
Layout Managers
FlowLayout
Default layout manager.
Places components from left to right until no
more items can be placed.
Can align each line left, center, or right.
Default alignment: LEFT.
GridLayout
Similar to FlowLayout.
All rows (columns) have same number of
components.
All components have the same size.
Layout Managers
BorderLayout
Items placed into one of five specific regions:
NORTH/SOUTH
EAST/WEST
CENTER
NORTH and SOUTH components extend
horizontally (completely span one edge to the
other).
EAST and WEST components extend vertically
between components in NORTH and SOUTH
regions.
CENTER component expands to occupy any
unused regions.
Sample
Code FlowLayoutDemo.java
import javax.swing.*;
import java.awt.*;
public class FlowLayoutDemo extends JFrame {
private JButton btnCalculate;
private JLabel lengthL;
public FlowLayoutDemo(){
super("Test Frame");
btnCalculate = new JButton("Calculate");
lengthL = new JLabel("Enter the length:");
Container pane =getContentPane();
pane.setLayout(new FlowLayout());
pane.add(lengthL);
pane.add(btnCalculate);
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
FlowLayoutDemo frame = new FlowLayoutDemo();
}
}
Sample
Code BorderLayoutDemo.java
import javax.swing.*;
import java.awt.*;
public class BorderLayoutDemo extends JFrame {
private JButton btnCalculate, btnExit;
private JLabel lengthL;
public BorderLayoutDemo(){
super("Test Frame");
btnCalculate = new JButton("Calculate");
btnExit = new JButton("Exit");
lengthL = new JLabel("Enter the length:");
Container pane =getContentPane();
pane.setLayout(new BorderLayout());
pane.add(lengthL, BorderLayout.EAST);
pane.add(btnCalculate, BorderLayout.SOUTH);
pane.add(btnExit, BorderLayout.WEST);
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
BorderLayoutDemo frame = new BorderLayoutDemo();
Sample GridLayoutDemo.java
Code
import javax.swing.*;
import java.awt.*;
public class GridLayoutDemo extends JFrame {
private JButton btnCalculate, btnExit;
private JLabel lengthL;
private JTextField lengthTF;
public GridLayoutDemo(){
super("Test Frame");
btnCalculate = new JButton("Calculate");
btnExit = new JButton("Exit");
lengthL = new JLabel("Enter the length:");
lengthTF = new JTextField(10);
Container pane =getContentPane();
pane.setLayout(new GridLayout(2,2));
pane.add(lengthL);
pane.add(lengthTF);
pane.add(btnCalculate);
pane.add(btnExit);
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Handling an Event
Action event: An 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.
Handling an Event
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.
Sample
Code EventDemo.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EventDemo extends JFrame {
private JButton btnCalculate, btnExit;
private JLabel lengthL,widthL, areaL;
private JTextField lengthTF, widthTF, areaTF;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public EventDemo(){
super("Test Frame");
btnCalculate = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
btnCalculate.addActionListener(cbHandler);
btnExit = new JButton("Exit");
ebHandler = new ExitButtonHandler();
btnExit.addActionListener(ebHandler);
lengthL = new JLabel("Enter the length:");
lengthTF = new JTextField(10);
widthL = new JLabel("Enter the width:");
widthTF = new JTextField(10);
Sample
Code EventDemo.java
areaL = new JLabel("Area:");
areaTF = new JTextField(10);
Container pane =getContentPane();
pane.setLayout(new GridLayout(4,2));
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(btnCalculate);
pane.add(btnExit);
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Sample
Code EventDemo.java
private class CalculateButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
double length, width, area;
length = Double.parseDouble(lengthTF.getText());
width = Double.parseDouble(widthTF.getText());
area = length * width;
areaTF.setText(String.format("%.2f",area));
}
}
private class ExitButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
public static void main(String[] args) {
EventDemo frame = new EventDemo();
}
}
Pseudocode for
EventDem.java
//Use the import statement to access the content pane
//Use the import statement to create GUI components
//Use the import statement to create event handling objects
//Define class EventDemo that extends JFrame
//Declare variables for each label, button, textfield and event handler of the content pane
//Write a default constructor which contain:
//Create each label fields
//Create each text fields
//Create a calculate button
//Register calculate button with event listener
//Create an exit button
//Register exit button with event listener
//Get the container object
//Set the pane layout
//Add the components in the pane
//Set the title for the window
//Set the size for the window
//Display the window
//Set the close operation for the window
//End constructor
//Define the main method which contain:
//declare a EventDemo variable and create an instance of EventDemo object
//End method main
//End class
TMA 3 (20%)
Individual Assignment
Submit soft copy (virus free) and hard copy of the TMA3 in word
processed (1.5 spacing).
You may send your soft copy to me at meemeng@yahoo.com
Submission date 21/10/07
Late submission
Over 7 days
Contact tutor before or on the due date
Over 8 – 14 days
Course Coordinator
Up to 21 days
Dean
TMA3 – Question 1
A) Write a java class FixedDepositMemory to
display a window screen to calculate Fixed
Deposit Maturity in a Bank.
B) write pseudocode for the program
C) Write complete java code for the program.
Useful Reference for TMA3
Formatting output
Malik textbook , page 142
LayoutManager
Malik textbook, page 888
Handling an Event
Malik textbook, page 322
Complete study chapter 6, Malik textbook
Applets
A Java program that is embedded within a
Web page and executed by a Web browser.
Create an applet by extending the class
JApplet.
class JApplet is contained in package
javax.swing.
Applets
Applets
No main method.
Methods init, start, and paint
guaranteed to be invoked in sequence.
To develop an applet:
Override any/all of the methods above.
Applet Methods
init method:
Initializes variables.
Gets data from user.
Places various GUI components.
paint method:
Performs output.
Skeleton of a Java Applet
import java.awt.Graphics;
import javax.swing.JApplet;
public class WelcomeApplet extends JApplet
{
}
Applet Displaying Welcome Message
//Welcome Applet
import java.awt.Graphics;
import javax.swing.JApplet;
public class WelcomeApplet extends JApplet
{
public void paint(Graphics g)
{
super.paint(g); //Line 1
g.drawString("Welcome to Java Programming" ,
30, 30); //Line 2
}
}
HTML to Run Applet
Differences Between Applets
and GUI Applications
Applets GUI applications
Derived from JApplet. Class extends JFrame.
No main method. Invokes main method.
Uses init method. Uses constructors.
Displayed by HTML. Uses method setVisible.
Sets title in HTML. Uses setTitle method.
Size set in HTML. Uses method setSize.
Applet closes when Closes with Exit button.
HTML doc closes.
Converting a GUI Application
to an Applet
Change JFrame to JApplet.
Change constructor to method init.
Remove method calls such as setVisible,
setTitle, setSize.
Remove the method main.
If applicable, remove Exit button and all
code associated with it (for example, action
listener).