building gui with awt
TRANSCRIPT
-
8/8/2019 Building GUI With AWT
1/75
Java
GUI building with the AWT
-
8/8/2019 Building GUI With AWT
2/75
2
A Simple Applet
-
8/8/2019 Building GUI With AWT
3/75
3
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
Javaplugin
appletviewer is a program that can run
An application is a Java program that runs all by itself
-
8/8/2019 Building GUI With AWT
4/75
4
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
-
8/8/2019 Building GUI With AWT
5/75
5
Applets cannot
Read or write to the local computers file system
If this were not the case, applets could potentially readsensitive data (credit card info!) or delete important files
Applets cannot find information about the localcomputer. For example user names and email addresses
Applets cannot run a local executable program (for
obvious reasons!)
-
8/8/2019 Building GUI With AWT
6/75
6
Applets cannot
Communicate with any host except its originatinghost Applets can onlyphonehome!
If this were not the case, applets could access web pages
behind corporate firewalls
They could then read potentially sensitive company
information
-
8/8/2019 Building GUI With AWT
7/75
7
How Applet works
-
8/8/2019 Building GUI With AWT
8/75
8
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/8/2019 Building GUI With AWT
9/75
9
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, thejavac will produce afile named
HelloWorld.class
-
8/8/2019 Building GUI With AWT
10/75
10
Building a Java Applet
Execution
Edit an HTML file to host the applet just created. The
HTML file will look like as:
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 appletviewertype the following:
appletviewer HelloJava.html
-
8/8/2019 Building GUI With AWT
11/75
29-Oct-10
Java Applet Skeleton/*
Program MyFirstApplet
An applet that displays the text "I Love Java"
and a rectangle around the text.
*/
import java.applet.*;
import java.awt.*;
public class HelloWorld extends Applet
{
public void paint( Graphics g)
{
g.drawString(HelloWorld",50,25);
}
}
Comment
Import
Statements
Class Name
Method Body
-
8/8/2019 Building GUI With AWT
12/75
12
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
-
8/8/2019 Building GUI With AWT
13/75
13
The java.awtpackage
awt stands forAbstract Window Toolkit
The java.awtpackage includes classes for:
Drawing lines and shapes
Drawing letters
Setting colors
Choosing fonts
If its drawn on the screen, then java.awt isprobably involved!
-
8/8/2019 Building GUI With AWT
14/75
14
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 doesnt return any result
-
8/8/2019 Building GUI With AWT
15/75
15
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 forGraphics context) is anobject 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 doesnt remember what youhave painted)
-
8/8/2019 Building GUI With AWT
16/75
16
Colors
The java.awtpackage defines a class named Color
There are 13 predefined colorshere are their fully-qualified names:
For compatibility with older programs (before the naming
conventions were established), Java also allows color
names in lowercase: Color.black, Color.darkGray, etc.
Color.BLACK Color.PINK Color.GREENColor.DARK_GRAY Color.RED Color.CYAN
Color.GRAY Color.ORANGE Color.BLUE
Color.LIGHT_GRAY Color.YELLOW
Color.WHITE Color.MAGENTA
-
8/8/2019 Building GUI With AWT
17/75
17
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)
-
8/8/2019 Building GUI With AWT
18/75
18
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
-
8/8/2019 Building GUI With AWT
19/75
19
Pixels
Apixel 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
-
8/8/2019 Building GUI With AWT
20/75
20
-
8/8/2019 Building GUI With AWT
21/75
21
Javas coordinate system
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
(0, 0)
(0, 20)
(50, 0)
(50, 20)
(w-1, h-1)
-
8/8/2019 Building GUI With AWT
22/75
22
Drawing rectangles
There are two ways to draw rectangles:
g.drawRect( left, top , width , height);
g.fillRect(left, top , width , height);
-
8/8/2019 Building GUI With AWT
23/75
23
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 );
-
8/8/2019 Building GUI With AWT
24/75
24
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);
}
}
-
8/8/2019 Building GUI With AWT
25/75
25
The HTML page
You can only run an applet in an HTML page
The HTML looks something like this:
DrawingApplet Applet
-
8/8/2019 Building GUI With AWT
26/75
26
Passing Parameter to Applet
C
orresponding HTML document containing this applet and providingparameter values will be :
< applet code = " RectangleTest" width = 150 height = 100 >
< param name = xValue value = 20 >
< param name = yValue value = 40 >
< param name = hValue value = 50 >
< /applet >
-
8/8/2019 Building GUI With AWT
27/75
27
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 );
}
}
-
8/8/2019 Building GUI With AWT
28/75
28
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);
}
}
FontFont
-
8/8/2019 Building GUI With AWT
29/75
29
The Life-Cycle of Applet
init()
Called exactly once in an applets life.
Called when applet is first loaded, which is after
object creation, e.g., when the browser visits theweb page for the first time.
Used to read applet parameters, start downloading
any other images or media files, etc.
-
8/8/2019 Building GUI With AWT
30/75
30
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.
-
8/8/2019 Building GUI With AWT
31/75
31
Applet Life-Cycle (Cont.)
destroy()
Called exactly once.
Called when the browser unloads the applet.
Used to perform any final clean-up.
-
8/8/2019 Building GUI With AWT
32/75
32
Browser Calling Applet Methods
Browser
invokes start()
Destroyed
Browser invokes
destroy()
Browser
invokes stop()
Loaded
Initialized
Browser
invokes init()
Started Stopped
Created
Browser creates
the applet
JVM loads the
applet class
Browser
invokes stop()
Browser
invokes start()
-
8/8/2019 Building GUI With AWT
33/75
33
To build a GUI...
Make somewhere to display thingsusually aFrame orDialog (for an application), or an Applet
Create some Components, such as buttons, text
areas, panels, etc. Add your Components to your display area
Arrange, orlay 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
-
8/8/2019 Building GUI With AWT
34/75
34
Containers and Components
The job of a Container is to hold and displayComponents
Some common subclasses ofComponent are Button,Checkbox, Label, Scrollbar, TextField, andTextArea
A Container is also a Component This allows Containers to be nested
Some Container subclasses are Panel (and Applet),Window, and Frame
-
8/8/2019 Building GUI With AWT
35/75
35
An Applet is Panel is a Container
java.lang.Object
|
+----java.awt.Component
|+----java.awt.Container
|
+----java.awt.Panel
|
+----java.applet.Applet
-
8/8/2019 Building GUI With AWT
36/75
36
Example: A "Life" applet
Container (Applet)
Containers (Panels)
Component (Canvas)
Components (Buttons)
Components (Labels)
Components (TextFields)
-
8/8/2019 Building GUI With AWT
37/75
37
Some types of components
Label Button
Button
Checkbox
Choice
List
Scrollbar
TextField TextArea
CheckboxGroupCheckbox
-
8/8/2019 Building GUI With AWT
38/75
38
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
-
8/8/2019 Building GUI With AWT
39/75
39
Inheritance tree of applets & framesObject
Component
Container
Window
Frame
Panel
Applet
Label
Canvas
Scrollbar
Choice
List
Button
Checkbox
TextComponent
-
8/8/2019 Building GUI With AWT
40/75
40
Object
Component
Button
TextComponent
Checkbox ChoiceContainer
Label
TextArea TextField
ScrollBar
Canvas
Panel ScrollPaneWindow
Part of the AWT Class Hierarchy
Dialog Frame
Applet
List
-
8/8/2019 Building GUI With AWT
41/75
41
-
8/8/2019 Building GUI With AWT
42/75
42
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,..
-
8/8/2019 Building GUI With AWT
43/75
43
Component, Container, and Panel
From AWT Container, applets get methods to holdcomponents & use layout managers.
Panels and applets can only be displayed on othergraphical surfaces.
A panel must be added to another container in order tobe displayed.
A component is added to a container by using add()from the Container class.
-
8/8/2019 Building GUI With AWT
44/75
44
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);
-
8/8/2019 Building GUI With AWT
45/75
45
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);...
-
8/8/2019 Building GUI With AWT
46/75
46
Creating a Frame
When you create an Applet, you get a Panel for free
When you write a GUI for an application, you need tocreate and use a Frame: Frame frame = new Frame();
frame.setTitle("My Frame");
frame.setSize(300, 200); // width, height
... addcomponents ...
frame.setVisible(true);
Or: class MyClass extends Frame {
...setTitle("My Frame"); // in some instance method
-
8/8/2019 Building GUI With AWT
47/75
47
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);
}
}
-
8/8/2019 Building GUI With AWT
48/75
48
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
-
8/8/2019 Building GUI With AWT
49/75
49
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
-
8/8/2019 Building GUI With AWT
50/75
50
Complete example: FlowLayout
import java.awt.*;
import java.applet.*;
public class FlowLayoutExample extends Applet {
public void init () {
setLayout (newFlowLayout ()); // defaultadd (new Button ("One"));
add (new Button ("Two"));
add (new Button ("Three"));
add (new Button ("Four"));
add (new Button ("Five"));
add (new Button ("Six"));}
}
-
8/8/2019 Building GUI With AWT
51/75
51
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);
-
8/8/2019 Building GUI With AWT
52/75
52
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);
}
-
8/8/2019 Building GUI With AWT
53/75
53
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);
}
}
-
8/8/2019 Building GUI With AWT
54/75
54
Using a Panel
Panel p = new Panel();
add (p, BorderLayout.SOUTH);
p.add (new Button ("Button 1"));
p.add (new Button ("Button 2"));
-
8/8/2019 Building GUI With AWT
55/75
55
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
-
8/8/2019 Building GUI With AWT
56/75
56
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"));}
}
-
8/8/2019 Building GUI With AWT
57/75
57
What is an Event in Java?
Sequential Execution
-
8/8/2019 Building GUI With AWT
58/75
58
Delegation Event Model
Event Source
SubscriberSubscribe
Notification
Subscribed listeners
-
8/8/2019 Building GUI With AWT
59/75
59
The Delegation Event Model
The concept is quite simple: a source generates an event andsends 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.
-
8/8/2019 Building GUI With AWT
60/75
60
Events
In the delegation model, an event is an object that describes astate change in a source. An eventcan be defined as a type of
signal to the program that something has happened.
The eventis an object generated by external user actionssuch 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 iscalled thesourceevent.
-
8/8/2019 Building GUI With AWT
61/75
61
Listeners
Listeners are interfaces, not classes
class MyButtonListener implements
ActionListener {
An interface is a group of methods that mustbe supplied
When you say implements, you are promisingto
supply those methods
-
8/8/2019 Building GUI With AWT
62/75
62
Writing a Listener
For a Button, you need an ActionListener
b1.addActionListener(new MyButtonListener ( ));
An ActionListener must have anactionPerformed(ActionEvent) method
public void actionPerformed(ActionEvent e) {
}
-
8/8/2019 Building GUI With AWT
63/75
63
MyButtonListener
public void init () {
...b1.addActionListener (new MyButtonListener ());
}
class MyButtonListener implements ActionListener {public void actionPerformed (ActionEvent e) {
showStatus ("Ouch!");
}
}
-
8/8/2019 Building GUI With AWT
64/75
64
Listeners forTextFields
An ActionListener listens for someone hitting theEnter 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)
-
8/8/2019 Building GUI With AWT
65/75
65
Event Listeners for Mouse and Keyboard EventsEvent Listeners for Mouse and Keyboard Events
Mou
seListenerMou
seListenerpublic void mouseEntered(MouseEvent e)
public void mouseExited (MouseEvent e)
public void mousePressed (MouseEvent e)
public void mouseReleased (MouseEvent e)
pu
blic void mou
seClicked (Mou
seEvent e)
KeyListenerKeyListener
public void keyPressed(KeyEvent e)
public void keyReleased(keyEvent e)
public void keyTyped(keyEvent e)
MouseMotionListenerMouseMotionListener
public void mouseMoved (MouseEvent e)
public void mouseDragged (MouseEvent e)
Pressed and released at same location
-
8/8/2019 Building GUI With AWT
66/75
66
Keyboard and Mouse EventsKeyboard 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 f unction and arrow keys from normal key
getModifiers setModifiers //retrieve/replace modifier keys
isAltDown, isShiftDown, isControlDown
-
8/8/2019 Building GUI With AWT
67/75
67
Keyboard and Mouse EventsKeyboard and Mouse Events
MouseEventMouseEvent methodsmethods:
getX, getY //determine location of the mouse event
getClickCount //differentiates between single and double clicks
getModifiers //to determine which button was pressed
h f ll i l
-
8/8/2019 Building GUI With AWT
68/75
68
The following example
Shows a simple user interface to select the backgroundcolour
This has been implemented as an applet so that it can be run with aweb browser
The normal Frameclass has been replaced with a Appletclass
Other small changes required ClassButtonPanelis the panel containing the push buttons and the
event handling (key parts emboldened)
-
8/8/2019 Building GUI With AWT
69/75
69
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;
}
-
8/8/2019 Building GUI With AWT
70/75
70
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);
}
-
8/8/2019 Building GUI With AWT
71/75
71
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();
}
-
8/8/2019 Building GUI With AWT
72/75
72
Blue RedYellow
yellowButton.addActionListener(this)
ButtonPanel
-
8/8/2019 Building GUI With AWT
73/75
73
Summary I: Building a GUI
Create a container, such as Frame or Applet
Choose a layout manager
Create more complex layouts by adding Panels; eachPanel can have its own layout manager
Create other components and add them to whicheverPanels you like
-
8/8/2019 Building GUI With AWT
74/75
74
Summary II: Building a GUI
For each active component, look up what kind ofListeners it canhave
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
-
8/8/2019 Building GUI With AWT
75/75
The End