Building GUI With AWT
Building GUI With AWT
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
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:
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:
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.*;
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
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)
(w-1, h-1)
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. * ;
27
Font
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
import java.applet.Applet;
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
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
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
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
38
Inheritance tree of applets & frames
Object
Component
Canvas
Label Container
List
Button
Choice
39
Part of the AWT Class Hierarchy
Object
Component
Applet
Dialog Frame
40
41
Inheriting from above classes
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());
51
BorderLayout with five Buttons
52
Complete example: BorderLayout
import java.awt.*;
import java.applet.*;
53
Using a Panel
54
GridLayout
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
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.
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.
60
Listeners
Listeners are interfaces, not classes
class MyButtonListener implements
ActionListener {
61
Writing a Listener
For a Button, you need an ActionListener
b1.addActionListener
(new MyButtonListener ( ));
62
MyButtonListener
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
67
The following example
68
class ButtonPanel extends Applet implements
ActionListener
{
public ButtonPanel()
{
// Create buttons and add listeners
}
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)
ButtonPanel
72
Summary I: Building a GUI
Create a container, such as Frame or Applet
73
Summary II: Building a GUI
For each active component, look up what kind of Listeners it can
have
74
The End
75