Java
GUI building with the AWT
A Simple Applet
2
Applets and applications
An applet is a Java program that runs on a web page
Applets can be run within any modern browser
To run modern Java applets, old browsers need an up-to-date
Java plugin
appletviewer is a program that can run
An application is a Java program that runs all by itself
3
Application vs. Applet
Application
Trusted (i.e., has full access to system resources)
Invoked by Java Virtual Machine (JVM, java), e.g.,
java HelloWorld
Should contain a main method, i.e.,
public static void main(String[])
Applet
Not trusted (i.e., has limited access to system resource to prevent security
breaches)
Invoked automatically by the web browser
Should be a subclass of class java.applet.Applet
4
Applets cannot
Read or write to the local computer’s file system
If this were not the case, applets could potentially read
sensitive data (credit card info!) or delete important files
Applets cannot find information about the local
computer. For example user names and email addresses
Applets cannot run a local executable program (for
obvious reasons!)
5
Applets cannot
Communicate with any host except its originating host
Applets can only phone home!
If this were not the case, applets could access web pages
behind corporate firewalls
They could then read potentially sensitive company
information
6
How Applet works
7
Building a Java Applet
Following piece of code is required:
// An applet to print Hello World! //
1. import java.awt.Graphics;
2. import java.applet.Applet;
3. public class HelloWorld extends Applet {
4. public void paint (Graphics g ) {
5. g.drawString("Hello World!“, 50, 25);
}
}
8
Building a Java Applet
Edit → Save → Compile
Edit the code in the same fashion as an Application
The name of the applet will be same as the public class,
here
HelloWorld.java
The program can be compiled in the same fashion as an
Application is compiled. That is,
javac HelloWorld.java
After successful compilation, the javac will produce a
file named
HelloWorld.class
9
Building a Java Applet
Execution
Edit an HTML file to host the applet just created. The HTML
file will look like as:
<applet code = HelloWorld.class width = 200 height = 100>
</applet>
Save this to file giving a file name HelloJava.html
Note: The name of the file not necessary be the same as the
name of the class; But extension should be same as the .html
Now the applet is ready for its execution!
To run with appletviewer type the following:
appletviewer HelloJava.html
10
Java Applet Skeleton
/*
Program MyFirstApplet Comment
Comment
An applet that displays the text "I Love Java"
and a rectangle around the text.
*/
Import
Import
import java.applet.*;
Statements
Statements
import java.awt.*;
public class HelloWorld extends Applet
{ Class
ClassName
Name
public void paint( Graphics g)
{
g.drawString(“HelloWorld",50,25); Method
MethodBody
Body
}
}
Dec 7, 2021
The Applet class
To create an applet, you must import the Applet class
This class is in the java.applet package
The Applet class contains code that works with a
browser to create a display window
Capitalization matters!
applet and Applet are different names
12
The java.awt package
“awt” stands for “Abstract Window Toolkit”
The java.awt package includes classes for:
Drawing lines and shapes
Drawing letters
Setting colors
Choosing fonts
If it’s drawn on the screen, then java.awt is
probably involved!
13
The paint method
Our applet is going to have a method to paint some
colored rectangles on the screen
This method must be named paint
paint needs to be told where on the screen it can draw
This will be the only parameter it needs
paint doesn’t return any result
14
The paint method, part 2
public void paint(Graphics g) { … }
public says that anyone can use this method
void says that it does not return a result
A Graphics (short for “Graphics context”) is an
object that holds information about a painting
It remembers what color you are using
It remembers what font you are using
You can “paint” on it (but it doesn’t remember what you
have painted)
15
Colors
The java.awt package defines a class named Color
There are 13 predefined colors—here are their fully-qualified
names:
Color.BLACK Color.PINK Color.GREEN
Color.DARK_GRAY Color.RED Color.CYAN
Color.GRAY Color.ORANGE Color.BLUE
Color.LIGHT_GRAY Color.YELLOW
Color.WHITE Color.MAGENTA
For compatibility with older programs (before the naming
conventions were established), Java also allows color
names in lowercase: Color.black, Color.darkGray, etc.
16
New colors
Every color is a mix of red, green, and blue
You can make your own colors:
new Color( red , green , blue )
Amounts range from 0 to 255
Black is (0, 0, 0), white is (255, 255, 255)
We are mixing lights, not pigments
Yellow is red + green, or (255, 255, 0)
17
Setting a color
To use a color, we tell our Graphics g what color we
want:
g.setColor(Color.RED);
g will remember this color and use it for everything
until we tell it some different color
18
Pixels
A pixel is a picture (pix) element
one pixel is one dot on your screen
there are typically 72 to 90 pixels per inch
java.awt measures everything in pixels
19
20
Java’s coordinate system
(0, 0) (50, 0)
(0, 20) (50, 20)
(w-1, h-1)
Java uses an (x, y) coordinate system
(0, 0) is the top left corner
(50, 0) is 50 pixels to the right of (0, 0)
(0, 20) is 20 pixels down from (0, 0)
(w - 1, h - 1) is just inside the bottom right corner, where w
is the width of the window and h is its height
21
Drawing rectangles
There are two ways to draw rectangles:
g.drawRect( left , top , width , height );
g.fillRect(left , top , width , height );
22
Some more java.awt methods
g.drawLine( x1 , y1 , x2 , y2 );
g.drawOval( left , top , width , height );
g.fillOval( left , top , width , height );
g.drawRoundRect( left , top , width , height );
g.fillRoundRect( left , top , width , height );
g.drawArc( left , top , width , height ,
startAngle , arcAngle );
g.drawString( string , x , y );
23
The complete applet
import java.applet.Applet;
import java.awt.*;
// Applet example
public class Drawing extends Applet {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(20, 20, 50, 30);
g.setColor(Color.RED);
g.fillRect(50, 30, 50, 30);
}
}
24
The HTML page
You can only run an applet in an HTML page
The HTML looks something like this:
<html>
<body>
<h1>DrawingApplet Applet</h1>
<applet code="Drawing.class"
width="250" height="200">
</applet>
</body>
</html>
25
Passing Parameter to Applet
Corresponding HTML document containing this applet and providing
parameter values will be :
< applet code = " RectangleTest" width = 150 height = 100 >
< param name = xValue value = 20 >
< param name = yValue value = 40 >
<param name = wValue value = 100>
< param name = hValue value = 50 >
< /applet >
26
Passing Parameter to Applet
// Use of init( ) to pass value through HTML to applet //
import java.awt . *;
import java.applet. * ;
public class RectangleTest extends applet {
int x, y, w, h;
public void init ( ) {
x = Integer.parseInt(getParameter (" xValue" ));
y = Integer.parseInt(getParameter (" yValue" ));
w = Integer.parseInt(getParameter (" wValue" ));
h = Integer.parseInt(getParameter (" hValue" ));
}
public void paint ( Graphics g ) {
g.drawRect (x, y, w, h );
}
}
27
Font
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
import java.applet.Applet;
public class HelloWorldApplet1 extends Applet {
Font f = new Font("TimesRoman", Font.BOLD, 36);
String name,greeting;
public void init() {
name = ”Peter Norton";
greeting = new String("Hello " + name + "!");
}
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.red);
g.drawString(greeting, 5, 40);
}
}
28
The Life-Cycle of Applet
init()
Called exactly once in an applet’s life.
Called when applet is first loaded, which is after
object creation, e.g., when the browser visits the
web page for the first time.
Used to read applet parameters, start downloading
any other images or media files, etc.
29
Applet Life-Cycle (Cont.)
start()
Called at least once.
Called when an applet is started or restarted, i.e.,
whenever the browser visits the web page.
stop()
Called at least once.
Called when the browser leaves the web page.
30
Applet Life-Cycle (Cont.)
destroy()
Called exactly once.
Called when the browser unloads the applet.
Used to perform any final clean-up.
31
Browser Calling Applet Methods
Loaded
JVM loads the
Browser creates
applet class
the applet
Created
Browser
invokes init()
Initialized
Browser Browser
invokes start() invokes stop()
Browser
invokes stop()
Started Stopped
Browser Browser invokes
invokes start() destroy()
Destroyed
32
To build a GUI...
Make somewhere to display things—usually a
Frame or Dialog (for an application), or an Applet
Create some Components, such as buttons, text
areas, panels, etc.
Add your Components to your display area
Arrange, or lay out, your Components
Attach Listeners to your Components
Interacting with a Component causes an Event to occur
A Listener gets a message when an interesting event
occurs, and executes some code to deal with it
33
Containers and Components
The job of a Container is to hold and display
Components
Some common subclasses of Component are Button,
Checkbox, Label, Scrollbar, TextField, and
TextArea
A Container is also a Component
This allows Containers to be nested
Some Container subclasses are Panel (and Applet),
Window, and Frame
34
An Applet is Panel is a Container
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container
|
+----java.awt.Panel
|
+----java.applet.Applet
35
Example: A "Life" applet
Container (Applet)
Containers (Panels)
Component (Canvas)
Components (Buttons)
Components (TextFields)
Components (Labels)
36
Some types of components
Label Button Checkbox
Choice Scrollbar
TextField List TextArea
Button
Checkbox CheckboxGroup
37
Panel and Canvas Classes
The Panel class is container subclass that is used to reserve a
rectangular portion of a Frame to place other components
The Canvas class is not a Container subclass, but does allow
you to reserve a portion of a Frame to draw in
38
Inheritance tree of applets & frames
Object
Component
Canvas
Label Container
List
Button
Scrollbar Panel Window
TextComponent
Checkbox Applet Frame
Choice
39
Part of the AWT Class Hierarchy
Object
Component
Button Checkbox Choice List Label Canvas
TextComponent Container ScrollBar
TextArea TextField Panel Window ScrollPane
Applet
Dialog Frame
40
41
Inheriting from above classes
Some methods in Component: add(), remove()
and setLayout(): controls the positions & sizes of
components.
Applets inherit the drawing and event handling
methods from AWT Component class to produce
user interfaces.
Drawing: images, control of color and font.
UI components: buttons, etc..
Event handling: detecting & responding to mouse dragging, button
pushing, key pressing,..
42
Component, Container, and Panel
From AWT Container, applets get methods to hold
components & use layout managers.
Panels and applets can only be displayed on other
graphical surfaces.
A panel must be added to another container in order to
be displayed.
A component is added to a container by using add()
from the Container class.
43
Creating components
Label lab = new Label ("Hi, Dave!");
Button but = new Button ("Click me!");
Checkbox toggle = new Checkbox ("toggle");
TextField txt =
new TextField ("Initial text.", 20);
Scrollbar scrolly = new Scrollbar
(Scrollbar.HORIZONTAL, initialValue,
bubbleSize, minValue, maxValue);
44
Adding components to the Applet
class MyApplet extends Applet {
public void init () {
add (lab); // same as this.add(lab)
add (but);
add (toggle);
add (txt);
add (scrolly);
...
45
Creating a Frame
When you create an Applet, you get a Panel “for free”
When you write a GUI for an application, you need to
create and use a Frame:
Frame frame = new Frame();
frame.setTitle("My Frame");
frame.setSize(300, 200); // width, height
... add components ...
frame.setVisible(true);
Or:
class MyClass extends Frame {
...
setTitle("My Frame"); // in some instance method
46
Frame Example
public class TwoButtons extends Frame {
Button redButton, blueButton;
public TwoButttons() {
super(“Two Buttons Frame”);
redButton = new Button(“Red”);
blueButton = new Button(“Blue”);
f.setLayout(new Flowlayout());
f.add(redButton);
f.add(blueButton);
f.setVisible(true);
}
}
47
Arranging components
Every Container has a layout manager
The default layout for a Panel is FlowLayout
An Applet is a Panel
Therefore, the default layout for a Applet is FlowLayout
You could set it explicitly with
setLayout (new FlowLayout( ));
You could change it to some other layout manager
48
FlowLayout
Use add(component); to add to a component when
using a FlowLayout
Components are added left-to-right
If no room, a new row is started
Exact layout depends on size of Applet
Components are made as small as possible
FlowLayout is convenient but often ugly
49
Complete example: FlowLayout
import java.awt.*;
import java.applet.*;
public class FlowLayoutExample extends Applet
{
public void init () {
setLayout (new FlowLayout ()); // default
add (new Button ("One"));
add (new Button ("Two"));
add (new Button ("Three"));
add (new Button ("Four"));
add (new Button ("Five"));
add (new Button ("Six"));
}
}
50
BorderLayout
At most five components can be
added
If you want more components, add a
Panel, then add components to it.
setLayout (new BorderLayout());
add (new Button("NORTH"), BorderLayout.NORTH);
51
BorderLayout with five Buttons
public void init() {
setLayout (new BorderLayout ());
add (new Button ("NORTH"), BorderLayout.NORTH);
add (new Button ("SOUTH"), BorderLayout.SOUTH);
add (new Button ("EAST"), BorderLayout.EAST);
add (new Button ("WEST"), BorderLayout.WEST);
add (new Button ("CENTER"), BorderLayout.CENTER);
}
52
Complete example: BorderLayout
import java.awt.*;
import java.applet.*;
public class BorderLayoutExample extends Applet {
public void init () {
setLayout (new BorderLayout());
add(new Button("One"), BorderLayout.NORTH);
add(new Button("Two"), BorderLayout.WEST);
add(new Button("Three"), BorderLayout.CENTER);
add(new Button("Four"), BorderLayout.EAST);
add(new Button("Five"), BorderLayout.SOUTH);
add(new Button("Six"), BorderLayout.SOUTH);
}
}
53
Using a Panel
Panel p = new Panel();
add (p, BorderLayout.SOUTH);
p.add (new Button ("Button 1"));
p.add (new Button ("Button 2"));
54
GridLayout
The GridLayout manager
divides the container up into
a given number of rows and
columns:
new GridLayout(rows, columns)
All sections of the grid are equally sized and as large as
possible
55
Complete example: GridLayout
import java.awt.*;
import java.applet.*;
public class GridLayoutExample extends Applet {
public void init () {
setLayout(new GridLayout(2, 3));
add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
}
}
56
What is an Event in Java?
Sequential Execution
57
Delegation Event Model
Subscriber
Subscribe
Event Source Notification
Subscribed listeners
58
The Delegation Event Model
The concept is quite simple: a source generates an event and
sends it to one or more listeners.
The listener simply waits until it receives an event. Once
received, the listener processes the event and then returns.
Listener must register with a source in order to receive an event
notification. This provides an important benefit: notifications
are sent only to listeners that want to receive them.
59
Events
In the delegation model, an event is an object that describes a
state change in a source. An event can be defined as a type of
signal to the program that something has happened.
The event is an object generated by external user actions
such as mouse movements, mouse button clicks, and
keystrokes, or by the operating system, such as a timer.
The GUI component on which an event is generated is
called the source event.
60
Listeners
Listeners are interfaces, not classes
class MyButtonListener implements
ActionListener {
An interface is a group of methods that must be supplied
When you say implements, you are promising to
supply those methods
61
Writing a Listener
For a Button, you need an ActionListener
b1.addActionListener
(new MyButtonListener ( ));
An ActionListener must have an
actionPerformed(ActionEvent) method
public void actionPerformed(ActionEvent e) {
…
}
62
MyButtonListener
public void init () {
...
b1.addActionListener (new MyButtonListener ());
}
class MyButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
showStatus ("Ouch!");
}
}
63
Listeners for TextFields
An ActionListener listens for someone hitting the
Enter key
An ActionListener requires this method:
public void actionPerformed (ActionEvent e)
You can use getText( ) to get the text
A TextListener listens for any and all keys
A TextListener requires this method:
public void textValueChanged(TextEvent e)
64
Event Listeners for Mouse and Keyboard Events
MouseListener
public void mouseEntered(MouseEvent e)
public void mouseExited (MouseEvent e)
public void mousePressed (MouseEvent e)
public void mouseReleased (MouseEvent e)
public void mouseClicked (MouseEvent e) Pressed and released at same location
MouseMotionListener
public void mouseMoved (MouseEvent e)
public void mouseDragged (MouseEvent e)
KeyListener
public void keyPressed(KeyEvent e)
public void keyReleased(keyEvent e)
public void keyTyped(keyEvent e)
65
Keyboard and Mouse Events
AWTEvent contains four important methods:
consume //delete the event
isConsumed //returns boolean – true if consumed by another
//listener on same source
getID //and int represening the event type
getSource //the Object that the event came from
KeyEvent adds the following methods:
getKeyChar //returns character typed
setKeyChar //replace the character with a different one
getKeyCode //returns an integer value which can be passedto
//getKeyText
isActionKey //differentiates function and arrow keys from normal key
getModifiers setModifiers //retrieve/replace modifier keys
isAltDown, isShiftDown, isControlDown
66
Keyboard and Mouse Events
MouseEvent methods:
methods
getX, getY //determine location of the mouse event
getClickCount //differentiates between single and double clicks
getModifiers //to determine which button was pressed
67
The following example
Shows a simple user interface to select the background
colour
This has been implemented as an applet so that it can be run with a
web browser
The normal Frame class has been replaced with a Applet class
Other small changes required
Class ButtonPanel is the panel containing the push buttons and the
event handling (key parts emboldened)
68
class ButtonPanel extends Applet implements
ActionListener
{
public ButtonPanel()
{
// Create buttons and add listeners
}
public void actionPerformed(ActionEvent evt)
{
// Handle button press events
}
private Button yellowButton;
private Button blueButton;
private Button redButton;
}
69
public ButtonPanel()
{
yellowButton = new Button("Yellow");
blueButton = new Button("Blue");
redButton = new Button("Red");
add(yellowButton);
add(blueButton);
add(redButton);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
}
70
public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
Color color = getBackground();
if (source == yellowButton) color = Color.yellow;
else if (source == blueButton) color = Color.blue;
else if (source == redButton) color = Color.red;
setBackground(color);
repaint();
}
71
yellowButton.addActionListener(this)
Yellow Blue Red
ButtonPanel
72
Summary I: Building a GUI
Create a container, such as Frame or Applet
Choose a layout manager
Create more complex layouts by adding Panels; each
Panel can have its own layout manager
Create other components and add them to whichever
Panels you like
73
Summary II: Building a GUI
For each active component, look up what kind of Listeners it can
have
Create (implement) the Listeners
often there is one Listener for each active component
Active components can share the same Listener
For each Listener you implement, supply the methods that it
requires
For Applets, write the necessary HTML
74
The End
75