ppt la10 java programming_05
TRANSCRIPT
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 2
Session Plan
Day 5
– Designing GUI
– Event Handling
– Applets
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 3
The java.awt Package
Java helps the programmer to create GUI with the classes in java.awt
AWT stands for Abstract Window Toolkit
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 4
Class Hierarchy
Component
Button
Label
WindowScrollbar
Canvas
Checkbox
Choice
Container
TextComponent
AppletPanel
Dialog
FrameTextField
TextArea
ScrollPane
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 5
Container Classes
Container classes are classes that can have other components on it
So for creating a GUI, we need at least one Container object
Three types of containers
– Panel : It is a pure container and is not a window in itself. The sole purpose
of a Panel is to organize the components on to a window.
– Frame : It is a fully functioning window with its own title and icons.
– Dialog : It can be thought of as a pop-up window that pops out when message
has to be displayed. It is not a fully functioning window like the Frame.
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 6
A Simple GUI Program
Just creating a Frame container without any components added to it
import java.awt.*;
class SimpleGUI{
public static void main(String args[]) {
Frame f = new Frame(“Simple GUI”);
f.setSize(300, 400);
f.setVisible(true);
}
} Making the Frame visible, without this statement, nothing will be
seen and should be the last statement after all components
have been added
Setting the size of the Frame
Calling the constructor of the Frame class and passing the title of the Frame as a String argument
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 7
import java.awt.*;
class SimpleGUI{
public static void main(String args[]){
Frame myFrame= new Frame(“Simple GUI”);
myFrame.setSize(300, 400);
myFrame.setBackground(Color.pink);
Button myButton = new Button(“Ok”);
myFrame.add(myButton);
myFrame.setVisible(true);
}
}
Adding Components
We can add Components to a Container
Creating a Button object and adding onto the container
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 8
Layout Managers
Each Container has a Layout Manager that will decide the size and position
of the Components placed on it ie each container has its default layout
The programmer can change the default Layout of the Container using the
method setLayout (which layout to follow)
The programmer can also cancel the default Layout of a Container by calling
the method setLayout (null)
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 9
Different Layouts (1 of 2)
There are 5 different layouts available
FlowLayout
– The components are placed horizontally one after another and then move to the next
line
GridLayout
– The components are placed in a grid (rows, columns)
BorderLayout
– 5 components can be added at the most
– The 5 borders are North, South, East, west and Center
– If not specified the default position is center in Border Layout
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 14
Different Layouts (2 of 2)
CardLayout
– The CardLayout places components/containers on top of each other like a deck of
cards
– Only one is visible at a time
– Every card is made visible using the method show()
GridBagLayout
– Most powerful and flexible
– It is a more advanced form of GridLayout where components can be placed
horizontally and vertically
– Components can be of different sizes and they can span multiple cells in the grid
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 18
Absolute Positioning
The programmer may take full control of positioning the components on the
container by doing absolute positioning
– setLayout(null);
– setBounds(x-cord, y-cord, width, height);
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 19
Checkbox
Checkboxes are used when you want to select 0 or more items from a set of items
The method getState() will return true if the Checkbox is selected
…
Checkbox c1 = new Checkbox(“English”);
Checkbox c2 = new Checkbox(“German”);
Checkbox c3 = new Checkbox(“French”);
…
if (c1.getState())
System.out.println(“The user knows English”);
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 20
CheckboxGroup
CheckboxGroup can be used to group some Checkbox objects together, so
that they become Radio Buttons
Radio Buttons are used when we want to select one and only one from a set of
items
…
CheckboxGroup cg = new CheckboxGroup();
Checkbox c1 = new Checkbox(“Morning”, cg, true);
Checkbox c2 = new Checkbox(“Evening”, cg, false);
Checkbox c3 = new Checkbox(“Night”, cg, false);
…
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 21
Choice
Choice is a Drop Down List
This is used to select 0 or more items from a set of items
The method getSelectedItem() will return the item selected by the user
– System.out.println(c.getSelectedItem());
…
Choice c = new Choice();
c.add(“Sunday”);
c.add(“Monday”);
…
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 22
List
List is a scrollable list of items
A list can be used to select 0 or more items from a set of items
The method getSelectedItem will return the item selected by the user
– System.out.println(l.getSelectedItem());
– getSelectedItems() returns a String[] if multiple items are selected
…
List list = new List();
List list = new List(5,true);
list.add(“Sunday”);
list.add(“Monday”);
…
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 24
Label
Label is a simple control used to display some message
– Label l = new Label(“Hello”)
The method setText can be used to set the message on the label
– l.setText(“Hello World”);
The method getText can be used to get the message from the label
– System.out.println(l.getText());
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 25
Scrollbar
Scrollbar is used to increment or decrement some value
The method getValue is used to get the current value of the Scrollbar
– System.out.println(s.getValue());
Scrollbar s = new Scrollbar(Scrollbar.HORIZONTAL,
25, 10, 0, 100);
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 26
TextField and TextArea
TextField and TextArea permits the user to type in some input
TextField is single line whereas TextArea is multi line
The method getText gets the text typed in by the user
– System.out.println(tf.getText());
…
TextField tf = new TextField(10);
TextArea ta = new TextArea(10, 20);
…
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 28
MenuBar, Menu and MenuItem (1 of 3)
The classes MenuBar, Menu and MenuItem help us to create a menu system
for the window
MenuBar is the area in the window where the menu system appears
– MenuBar mb = new MenuBar();
A menu system can be added to a window by setting a MenuBar to this window
– f.setMenuBar(mb); (where f is the Frame reference)
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 29
MenuBar, Menu and MenuItem (2 of 3)
The different items that appear on the MenuBar are represented by the class
Menu
A Menu can be added to a MenuBar using the add method
…
Menu m1 = new Menu(“File”);
Menu m2 = new Menu(“Edit”);
Menu m3 = new Menu(“Help”);
…
…
mb.add(m1);
mb.add(m2);
…
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 30
MenuBar, Menu and MenuItem (3 of 3)
The items that drop down when you select a Menu are objects of MenuItem
A MenuItem can be added to a Menu using the method add
…
MenuItem menuitem1 = new MenuItem(“Open”);
MenuItem menuitem2 = new MenuItem(“New”);
…
…
m1.add(mi1);
m1.add(mi2);
…
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 31
Panel
Panel is a Container and can contain other Components
Generally we do not use Panel as the main Container since it is not a
Window
Panel can be used to logically group some Components together
We can add three Panels to a Frame, each Panel can have a different Layout
and Components can be added to the Panels
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 32
Dialog
Dialog is a Window that is used to display some message and get a
response from the user
For example, a small window that asks the user “Are you sure?” can be
implemented using Dialog
The Dialog can have two Buttons also that says “Yes” and “No”
The method dispose() helps to dispose the dialogbox
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 33
Events
Events correspond to :
– Physical actions (E.g.: mouse button down, Key press/release)
– Logical events (E.g.: gotfocus - receiving focus on a component)
Event is an encapsulation of some input delivered asynchronously to the
application
The java.awt.event package defines classes to represent different type of
events.
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 34
Event Handling Mechanisms
Delegation event model – The new approach
Concept :
– Source generates the events and sends them to one or more listeners
– Listener waits until it receives an event
– Once received, the listener processes the event and then returns
Event handling is totally separated from UI component
A UI is able to "delegate" the event handling procedure to a separate piece of
code
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 35
Hierarchy of Event Classes in java.awt.event
EventObject
AWTEvent
Action Event AdjustmentEvent ComponentEvent ItemEvent TextEvent
ContainerEvent FocusEvent InputEvent PaintEvent WindowEvent
KeyEvent Mouse Event
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 36
Main Event Classes in java.awt.event (1 of 2)
EVENT CLASS DESCRIPTION LISTENER
ActionEvent Generated when a button is pressed. ActionListener
AdjustmentEvent Generated when a scroll bar is used. AdjustmentListener
ComponentEventGenerated when a component is moved, resized,
shown or hidden.ComponentListener
ContainerEventGenerated when a component is added or removed
from the container.ContainerListener
FocusEventGenerated when a component gains or loses
keyboard focusFocusListener
InputEventAbstract superclass for all component input event
classes.
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 42
Main Event Classes in java.awt.event (2 of 2)
EVENT CLASS DESCRIPTION LISTENER
ItemEvent Generated when a check box or list item is clicked ItemListener
KeyEvent Generated when input is received from the keyboard. KeyListener
MouseEventGenerated when the mouse is moved, dragged,
clicked, or released.MouseListener
TextEventGenerated when the value of a text area or text field is
changed. TextListener
WindowEventGenerated when a window is activated, closed,
deactivated, deiconified, iconified, opened.WindowListener
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 47
Using the delegation event model
Create a Listener
object which
implements the
listener interface.
Associate a Listener
with the source
public class MyApplication{
...
Button button = new Button("I'm a button!");
button.addActionListener(new MyHandler());
}
public class MyHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
numClicks++;
}
}
Method in the interface (ActionListener)
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 48
Adapter Classes (1 of 2)
While implementing an interface, we must implement all the methods listed in
the interface
E.g., the MouseListener interface contains five methods: mousePressed,
mouseReleased, mouseEntered, mouseExited, and mouseClicked
If you don’t want to implement some methods, you must have empty bodies of
code for those methods
Difficult to read the code, and maintain it !
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 49
Adapter Classes (2 of 2)
Adapter classes help you avoid implementing empty method bodies
The Java API includes an adapter class for each listener interface with more
than one method.
For example, the MouseAdapter class implements the MouseListener
interface.
An adapter class implements empty versions of all its interface's methods.
Instead of implementing the listener interface, one can extend the
corresponding adapter class and implement only the necessary method(s)
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 50
Anonymous inner class
Sometimes, anonymous inner classes are used for event handling
The general syntax for an anonymous inner class is:
…
b.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae){
System.out.println(“Button Clicked”);
}
});
…
Declaring a class without a name which implements the
ActionListener interface. The class declaration and
instantiation is happening in the same step
new <BaseClassName/InterfaceName>(){
//method implementations
}
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 51
Applets
A Java class that can be embedded within a HTML page and downloaded
and executed by a web browser
An applet can be used to enhance the features of a Web Page
The applet runs on JVM embedded in the browser
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 52
Applets
Applet is a container class that is available in java.applet package
We can create our own Applets by extending the Applet class
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 53
Lifecycle of an Applet (1 of 3)
Applet Working
Applet Displayed
Idle State
Applet Destroyed
start( )
paint( )
stop( )
destroy( )
Draw/Redraw Applet
Destroy Applet
init( )Start State
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 54
Lifecycle of an Applet (2 of 3)
The browser calls the init method of the Applet, followed by the start method
If the users leaves the web page, the browser will call the stop method of the
Applet
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 55
Lifecycle of an Applet (3 of 3)
If the user comes back to the page the browser will call the start method of the
Applet again
The destroy method is called just before the applet is finally unloaded from
memory
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 56
Execution of an applet (1 of 2)
Compile the applet program, say MyApplet.java, to get the .class file,
MyApplet.class
Embed the <applet></applet> tags in a html file as follows
– Code, width and height are mandatory attributes for the applet tag
Use any java compatible browser to run the html file
<applet code=“MyApplet" width=200 height=200>
</applet>
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 57
Execution of an applet (2 of 2)
For testing an Applet, we can use the appletviewer tool which is in
<javahome>\bin directory
Type the applet tag alone in a file, say applet.txt, and type the following
command
– appletviewer applet.txt
Instead of creating a separate file, the applet tag can be included as a
comment in MyApplet.java file itself. The command will now be as follows
– appletviewer MyApplet.java
The appletviewer tool will open a window to display the Applet
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 58
Parameter passing to an applet
Parameters are passed into an applet as name-value pair using the param
tag within applet tag
– <applet code="ParameterApplet" width=200 height=200>
<param name=“name” value=“value">
</applet>
The values are passed as String values
getParameter (String parameterName) returns the value
ER/CORP/CRS/LA10/003
Version 1.00Copyright © 2005, Infosys
Technologies Ltd 59
Summary
Abstract Window Toolkit basics
Abstract Window Toolkit controls
Layout Managers
Event Handling Mechanisms
Event Model
APIs to handle events
Applets