Advanced Programming: Computer Science Program
Advanced Programming: Computer Science Program
2
Objective
Within this chapter you will be introduced to many of the
Java components for constructing graphical user interfaces
(GUIs).
With the information in this chapter you will be able to
develop your own GUIs.
3
Introduction
A graphical user interface (GUI) presents a user-friendly
mechanism for interacting with an application.
A GUI gives an application a distinctive “look” and “feel”.
There are two main sets of visual components and
containers for user interface design in JAVA:
AWT (Abstract Window Toolkit) - in package java.awt and
Swing - in package javax.swing
4
AWT vs. Swing
AWT is fine for developing simple graphical user interfaces, but
not for developing comprehensive GUI projects.
Besides, AWT is prone to platform-specific bugs.
The AWT user-interface components were replaced by a more
robust, versatile, and flexible library known as Swing
components.
Swing components depend less on the target platform and use
less of the native GUI resource.
Swing components are painted directly on canvases using Java
code.
For this reason, Swing components that don’t rely on native GUI
are referred to as lightweight components, and AWT components
are referred to as heavyweight components.
5
AWT vs. Swing (cont’d)
AWT features include:
A rich set of user interface components.
A robust event-handling model.
Graphics and imaging tools, including shape, color, and font classes.
Swing features include:
All the features of AWT.
100% Pure Java certified versions of the existing AWT
component set (Button, Scrollbar, Label, etc.).
A rich set of higher-level components (such as tree view, list
box, and tabbed panes).
Pure Java design, no reliance on peers.
Pluggable Look and Feel.
6
Java GUI API
The GUI API contains classes that can be classified into
three groups:
component classes,
container classes, and
helper classes.
7
Java GUI API (cont’d)
8
Java GUI API (cont’d)
Class Object is the super class of the Java class hierarchy.
Component is the root class of all the user-interface
classes including container classes.
JComponent is the root class of all the lightweight Swing
components.
An instance of Container can hold instances of
Component.
Window, Panel, Applet, Frame, and Dialog are the
container classes for AWT components.
To work with Swing components, use Container, JFrame,
JDialog, JApplet, and Jpanel.
9
Java GUI API (cnt’d)
10
Frames
To create a user interface, you need to create either a
frame or an applet to hold the user-interface
components.
A top-level window (that is, a window that is not
contained inside another window) is called a frame in
Java.
A Frame has:
a title bar (containing an icon, a title, and the
minimize/maximize(restore-down)/close buttons),
an optional menu bar and
the content display area.
To create a frame, use the JFrame class
11
Frame
Example 1
import javax.swing.JFrame;
public class MyFrame {
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("MyFrame");
frame.setSize(400, 300); // Set the frame size
// Center a frame
frame.setLocationRelativeTo(null); //or .setLocation(300,200)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Display the frame
}
}
12
Frame (cont’d)
13
Frame (cont’d)
Adding Components to a Frame
import javax.swing.JFrame;
import javax.swing.JButton;
public class FrameWithButton {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrame");
// Add a button into the frame
JButton jbtOK = new JButton("OK");
frame.add(jbtOK);
frame.setSize(400, 300);
frame.setLocation(360,360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
14
Frame (cont’d)
Adding Lablel
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FrameWithLabel {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrame");
// Add a lable into the frame
JLabel jLblName = new JLabel(“First Name");
frame.add(jLblName);
frame.setSize(400, 300);
frame.setLocation(360,360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
15
Layout Managers
Java’s layout managers provide a level of abstraction that
automatically maps your user interface on all window
systems.
The Java GUI components are placed in containers, where
they are arranged by the container’s layout manager.
Layout managers are set in containers using the
setLayout(aLayoutManager) method.
This section introduces three basic layout managers:
FlowLayout, GridLayout, and BorderLayout.
16
FlowLayout
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 is filled, a new row is
started.
You can specify the way the components are aligned by using one of
three constants:
FlowLayout RIGHT,
FlowLayout.CENTER, or
FlowLayout.LEFT.
You can also specify the gap between components in pixels.
17
FlowLayout (cont’d)
EXAMPLE
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.FlowLayout;
19
GridLayout
Arranges components in a grid (matrix) formation.
The components are placed in the grid from left to
right, starting with the first row, then the second, and
so on, in the order in which they are added.
20
GridLayout (cont’d)
EXAMPLE
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.GridLayout;
Output
22
BorderLayout
Divides a container into five areas: East, South, West,
North, and Center.
Components are added to a BorderLayout by using
add(Component, index), where index is a constant
BorderLayout.EAST,
BorderLayout.SOUTH,
BorderLayout.WEST,
BorderLayout.NORTH, or
BorderLayout.CENTER.
23
BorderLayout
EXAMPLE
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class ShowBorderLayout extends JFrame
{
public ShowBorderLayout() {
// Set BorderLayout with horizontal gap 5 and vertical gap 10
setLayout( new BorderLayout(5, 10));
// Add buttons to the frame
add(new JButton("East"), BorderLayout.EAST);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("Center"), BorderLayout.CENTER);
}
24
BorderLayout (cont’d)
/** Main method */
public static void main(String[] args) {
ShowBorderLayout frame = new ShowBorderLayout();
frame.setTitle("ShowBorderLayout");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output
25
Panels
With Java GUI programming, you can divide a window
into panels.
Panels act as subcontainers to group user-interface
components.
You add the buttons in one panel, then add the panel
into the frame.
You can use new JPanel() to create a panel with a
default FlowLayout manager or new
Panel(LayoutManager) to create a panel with the
specified layout manager.
26
Panels (cont’d)
Example 1
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.BorderLayout;
public class SimplePanel1 extends JFrame {
public SimplePanel1() {
// Create panel p1 for the buttons and set GridLayout
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 2));
//Add label and text field to the panel
p1.add(new JLabel("First Name"));
p1.add(new JTextField(8));
// Create panel p2 to hold a p1
JPanel p2 = new JPanel(new BorderLayout());
p2.add(p1, BorderLayout.NORTH);
p2.add (new JButton("Button in Panel 2"));
// add contents into the frame
add(p2);
} 27
Panels (cont’d)
/** Main method */
public static void main(String[] args) {
SimplePanel1 frame = new SimplePanel1();
frame.setTitle("Panel With Components");
frame.setSize(300, 100);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
28
Panels (cont’d)
Example 2
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.BorderLayout;
29
Panels (cont’d)
p1.add(new JButton("" + 0));
p1.add(new JButton("Start"));
p1.add(new JButton("Stop"));
30
Panels (cont’d)
/** Main method */
public static void main(String[] args) {
TestPanels frame = new TestPanels();
frame.setTitle("The Front View of a Microwave Oven");
frame.setSize(400, 250);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output
31
The Font Class
You can create a font using the java.awt.Font class and set
fonts for the components using the setFont method in the
Component class.
The constructor for Font is:
Font(String name, int style, int size);
You can choose a font name from SansSerif, Serif,
Monospaced, Dialog, or DialogInput,
Choose a style from Font.PLAIN (0), Font.BOLD (1),
Font.ITALIC (2), and Font.BOLD Font.ITALIC (3), and
specify a font size of any positive integer.
32
Font (cont’d)
Example:
Font font1 = new Font("SansSerif", Font.BOLD, 16);
Font font2 = new Font("Serif", Font.BOLD + Font.ITALIC, 12);
JButton jbtOK = new JButton("OK");
jbtOK.setFont(font1);
33
The Color Class
You can set colors for GUI components by using the
java.awt.Color class.
Colors are made of red, green, and blue components, each
represented by an int value that describes its intensity,
ranging from 0 (darkest shade) to 255 (lightest shade).
You can create a color using the following constructor:
public Color(int r, int g, int b);
Example:
Color color = new Color(128, 100, 100);
You can use the setBackground(Color c) and
setForeground(Color c) methods to set a component’s
background and foreground colors.
34
The Color Class (cont’d)
Example
JButton jbtOK = new JButton("OK");
jbtOK.setBackground(color);
jbtOK.setForeground(new Color(100, 1, 1));
Alternatively, you can use one of the 13 standard colors
(BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN,
LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE,
and YELLOW) defined as constants in java.awt.Color.
The following code, for instance, sets the foreground color
of a button to red:
jbtOK.setForeground(Color.RED);
35
The Color Class (cont’d)
Example
import java.awt.GridLayout;
import java.awt.Color;
import javax.swing.*;
public class ColorExample extends JFrame{
public ColorExample(){
JFrame jf = new JFrame("Color Frame");
setLayout(new GridLayout(1,2));
Color color = new Color(128, 100, 100);
JButton bc1 = new JButton("Left Button");
JButton bc2 = new JButton("Right Button");
bc1.setBackground(color);
bc2.setForeground(new Color(250,0, 0));
//bc2.setForeground(Color.BLUE);
add(bc1);
add(bc2);
}
36
The Color Class (cont’d)
public static void main(String[] args){
ColorExample ce = new ColorExample();
ce.setSize(300,150);
ce.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ce.setLocationRelativeTo(null);
ce.setVisible(true);
}
}
37
Image Icons
import javax.swing.*;
import java.awt.*;
public class ImageExample extends JFrame {
public ImageExample() {
ImageIcon homeIcon = new ImageIcon("src/home.gif");
ImageIcon birdIcon = new ImageIcon("src/bird.gif");
ImageIcon mailIcon = new ImageIcon("src/mail.gif");
setLayout(new GridLayout(1, 3, 5, 5));
add(new JLabel(homeIcon));
add(new JButton(birdIcon));
add(new JLabel(mailIcon));
38
Image Icons (cont’d)
39
Event Handling
Event and Event Source
When you run a Java GUI program, the program interacts with
the user, and the events drive its execution.
An event can be defined as a signal to the program that
something has happened.
Events are triggered either by external user actions, such as
mouse movements, button clicks, and keystrokes, or by
internal program activities, such as a timer.
The program can choose to respond to or ignore an event.
The component that creates an event and fires it is called the
source object or source component.
For example, a button is the source object for a button-clicking
action event.
An event is an instance of an event class.
40
Event Handling
Java has a number of events and event handlers.
Java.awt.event –is the main package
It is up to the programmer to decide what to be
executed, how to handle the generated event, etc
There are more than 16 event types in java.
Eventhandler and ActionListener are the two
important aspects in event manipulation
Adding Listener helps to organize the action(event) to
be done after the button or the GUI control is selected
ActionListner is the main Interface in event handling
41
Event Handling (cont’d)
42
Event Handling (cont’d)
Listeners, Registrations, and Handling Events
Java uses a delegation-based model for event handling:
a source object fires an event, and an object interested in the
event handles it. The latter object is called a listener.
For an object to be a listener for an event on a source object,
two things are needed:
The listener object must be an instance of the corresponding
event-listener interface to ensure that the listener has the correct
method for processing the event. The following table lists event
types, the corresponding listener interfaces, and the methods
defined in the listener interfaces.
The listener object must be registered by the source object.
Registration methods depend on the event type. For ActionEvent,
the method is addActionListener.
43
Event Handling (cont’d)
Example 1
import javax.swing.*;
import java.awt.event.*;
44
Event Handling (cont’d)
// Register listeners
OKListenerClass listener1 = new OKListenerClass();
CancelListenerClass listener2 = new CancelListenerClass();
jbtOK.addActionListener(listener1);
jbtCancel.addActionListener(listener2);
}
45
Event Handling (cont’d)
class OKListenerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("OK button clicked");
}
}
46
Event Handling (cont’d)
Example 2
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
48
Example 3
import javax.swing.*; // Packages used
import java.awt.*;
import java.awt.event.*;
public class Converter extends JFrame implements ActionListener{
private JLabel prompt = new JLabel("Distance in miles: ");
private JTextField input = new JTextField(6);
private JTextArea display = new JTextArea(10,20);
private JButton convert = new JButton("Convert!");
public Converter() {
setLayout(new FlowLayout());
add(prompt);
add(input);
add(convert);
add(display);
display.setLineWrap(true);
display.setEditable(false);
convert.addActionListener(this);
} // Converter()
49
public void actionPerformed( ActionEvent e ) {
display.setText("");
double km = miles/0.62;
display.append(miles + " miles equals " + km + " kilometers\n");
} // actionPerformed()
50
public static void main(String args[]) {
Converter f = new Converter();
f.setSize(400, 300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0); // Quit the application
}
});
} // main()
} // Converter class
51
More Examples
Checkbox- CheckBoxTest.java
Text Area – TextArea.java
Combobox – ComboBoxDemo.java – uses
DescriptionPanel.java class
Lists – ListTest.java
Tree – SimpleTree.java
Menu – SimpleTextEditor.java
Progress Indicators – ProgressBarDemo.java
52
Overview of Java Applets
Applet is a browser dependent program of java
In applet, methods like init(),paint() etc are included
There is no main() method in applet
Package:- import java.applet.*;
Java application uses JFrame but java applet uses
JApplet
Java application saved by filename.java and run by
javac filename
But, java applets needs another html file and save
by filename.html and run by appletviewer
filename.html
53
Cont..
Basic drawing Tools:
Some of the known functions for drawing are:
drawLine()-x,y coordinates and length and height
drawRect();
fillRect();
drawPolygon()
drawOval();
drawstring();-gin-bcoordinates, end-coordinates
54
Cont..
for irregular shapes-we use drawPolygon()
eg:
int x[]={10,20,30,40,50,60};
int y[]={60,50,40,30,20,10};
int p=6;
drawPolygon(x,y,p);//hexagon
55
Examples
Eg1: public class eg1 extends Japplet{
Public void init()
{setBackground(Color.red);
}
Public void paint(Graphics g)
{ g.setColor(Color.blue);
g.fillRect(0,0,100,100);
}
}
56
Examples
import java.awt.*;
import java.applet.*;
public class Applet1 extends JApplet {
public void paint(Graphics g)
{
g.fillRect(30, 20, 200, 200);
g.clearRect(50, 30,70,50);
g.drawRect(60,50,40,20);
g.drawLine(10,50,250,55);
}}
57
Examples(applet)
Eg html file for a java class name Eg;
<html>
<head>the result</head>
<body>
<applet code=”Eg.class” width=250 height=250>
</applet></body></html>
58
Group Assignments
Read and write some concepts about those questions at
list 5 pages.
1. Applet.
2. AWT vs. Swing.
3. Design and develop GUI using java program with
Panels.
4. Write the java program by performing Event Handling
actions.
59