Svcet: Event Driven Programming
Svcet: Event Driven Programming
UNIT-5
Java AWT
The Abstract Window Toolkit (AWT) is Java’s original platform-independent window-
ing, graphics, and user-interface widget toolkit. The AWT classes are contained in the
java.awt package.
• Contains all of the classes for creating user interfaces and for painting graphics and
images.
•
ET
an API to develop GUI or window-based applications in java.
The hierarchy of Java AWT classes are shown below.
C
SV
Component
A component is an object having a graphical representation that can be displayed on the
screen and that can interact with the user.
Examples :
buttons, checkboxes, and scrollbars
The Component class is the abstract superclass of all user interface elements that are
displayed on the screen. A Component object remembers current text font, foreground and
background color.
Container
The Container class is the subclass of Component. The container object is a component
that can contain other AWT components. It is responsible for laying out any components that
it contains.
Window
The class Window is a top level window with no border and no menubar. The default lay-
ET
out for a window is BorderLayout. A window must have either a frame, dialog, or another
window defined as its owner when it’s constructed.
Panel
C
The class Panel is the simplest container class. It provides space in which an application
can attach any other component, including other panels. The default layout manager for a
panel is the FlowLayout layout manager
SV
Frame
A Frame is a top-level window with a title and a border. It uses BorderLayout as default
layout manager.
Dialog
A Dialog is a top-level window with a title and a border that is typically used to take some
form of input from the user.
Canvas
A Canvas component represents a blank rectangular area of the screen onto which the
application can draw or from which the application can trap input events from the user. An
application must subclass the Canvas class in order to get useful functionality such as creat-
ing a custom component. The paint method must be overridden in order to perform custom
graphics on the canvas. It is not a part of hierarchy of Java AWT.
java.awt.Graphics class
The java.awt.Graphics class provides many methods for graphics programming. A graph-
ics context is encapsulated by the Graphics class and is obtained in two ways:
• It is passed to an applet when one of its various methods, such as paint( ) or
update( ) is called.
• It is returned by the getGraphics( ) method of Component.
Graphics Methods
The commonly used methods of Graphics class are as follows.
Method Description
abstract Graphics create() Creates a new Graphics object that is a
copy of this Graphics object
abstract void drawString(String str, int Draws the text given by the specified
x, int y) string
void drawRect(int x, int y, int width, intdraws a rectangle with the specified width
ET
height) and height
void draw3DRect(int x, int y, int width, Draws a 3-D highlighted outline of the
int height, boolean raised) specified rectangle.
abstract void drawRoundRect(int x, int Draws an outlined round-cornered rect-
C
y, int width, int height, int arcWidth, int
angle using this graphics context’s current
arcHeight) color
abstract void fillRect(int x, int y, int fill rectangle with the default color and
SV
abstract void fillArc(int x, int y, int width, fill a circular or elliptical arc.
int height, int startAngle, int arcAngle)
abstract void setColor(Color c) set the graphics current color to the speci-
fied color.
abstract void setFont(Font font) set the graphics current font to the speci-
fied font.
Example:
GraphicsDemo.java
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red); // set font color
ET
g.drawString(“Welcome”,50, 50); // display text
g.drawLine(120,120,200,300); // draw a line
// draw and fill rectangle
C
g.drawRect(170,100,60,50);
g.fillRect(170,100,60,50);
SV
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}
}
Test.html
<html>
<body>
<applet code=”GraphicsDemo4.class” width=”300” height=”300”>
</applet>
</body>
</html>
Sample Output:
ET
C
SV
Note:
Steps to be followed to compile and run applet in DOS.
1. Compile the java file using javac command (for example, javac GraphicsDemo.
java).
2. Create a separate html file. Mention the name of the java class file in the applet code
parameter (for example code=”GraphicsDemo.class”)
3. Run the html file using appletviewer command (for example, appletviewer test.html)
Frames
A Frame is a top-level window with a title and a border. Frames are capable of generating
the following types of window events: WindowOpened, WindowClosing, WindowClosed,
WindowIconified, WindowDeiconified, WindowActivated, WindowDeactivated.
Frame Constructor
Frame()
ET
Constructs a new instance of Frame that is initially invisible.
Frame(String)
Constructs a new, initially invisible Frame object with the specified title.
Some of the commonly used methods of Frame class are as follows.
C
Methods Description
SV
label can be added to the current frame by creating an Label instance and calling the add()
method.
Example:
import java.awt.*;
frm.add(lbl);
ET
frm.setSize(400,400);
frm.setVisible(true);
C
}
}
SV
Sample Output:
ET
Creating an Frame Window in an Applet
The steps to be followed to create a child frame within an applet are as follows.
C
}
public void windowClosing(WindowEvent we) {
sampleFrame.setVisible(false);
}
}
// Create frame window.
public class AppletFrame extends Applet {
Frame f;
//init(), start(), paint(), and stop() methods are called automatically in the specified se-
quence.
public void init() {
f = new SampleFrame(“A Frame Window”);
f.setSize(150, 150);
f.setVisible(true);
}
public void start() {
f.setVisible(true); // make the window visible
}
public void stop() {
f.setVisible(false); // hide the window
}
public void paint(Graphics g) {
g.drawString(“This is in applet window”, 15, 30); // Display the given text in the win-
dow
}
}
ET
Test1.html
<html>
<body>
C
</applet>
</body>
</html>
Sample Output:
Components
Java AWT Component classes exist in java.awt package. The Component class is a super
class of all components such as buttons, checkboxes, scrollbars, etc.
Component class constructor:
Component() // constructs a new component
Properties of Java AWT Components:
• A Component object represents a graphical interactive area displayable on the screen
that can be used by the user.
• Any subclass of a Component class is known as a component. For example, button
is a component.
• Only components can be added to a container, like frame.
Some of the commonly used methods of Component class are as follows.
Method Description
ET
setBackground(Color) Sets the background color of this component.
setBounds(int, int, int, int) Moves and resizes this component.
setEnabled(boolean) Enables or disables this component, depending on the
value of the parameter b.
C
setFont(Font) Sets the font of this component.
setForeground(Color) Sets the foreground color of this component.
SV
g2d.setColor(Color.black);
g2d.drawString(“Graphics2D Example”,120.0f,100.0f);
g2d.setColor(Color.green);
g2d.drawLine(100,100,300,200);
g2d.drawOval(150,150,100,200);
g2d.fillOval(150,150,100,200);
}
}
Sample Output:
ET
C
Colors in Java
SV
To support different colors Java package comes with the Color class. The Color class
states colors in the default sRGB color space or colors in arbitrary color spaces identified by
a ColorSpace.
Color class static color variables available are:
Color.black Color.lightGray
Color.blue Color.magenta
Color.cyan Color.orange
Color.darkGray Color.pink
Color.gray Color.red
Color.green Color.white
Color.yellow
Color class constructor
Color(float r, float g, float b) – create color with specified red, green, and blue values in
the range (0.0 - 1.0)
Color(int r, int g, int b)- create color with the specified red, green, and blue values in the
range (0 - 255).
Some of the commonly used methods supported by the Color class are as follows.
Method Description
int getRed() Returns the red component in the range 0-255 in the
default sRGB space.
Returns the green component in the range 0-255 in the
int getGreen() default sRGB space.
int getBlue() Returns the blue component in the range 0-255 in the
default sRGB space.
Color getHSBColor(float h, Creates a Color object based on the specified values for
float s, float b) the HSB color model.
The current graphics color can be changed using setColor() method defined in Graphics
class.
void setColor(Color newColor) // newColor indicates new drawing color
ET
The current color detail can be obtained using getColor() method. Its syntax is.
Color getColor()
Example:
C
import java.awt.*;
import java.applet.*;
SV
/*
<applet code=”ColorDemo” width=350 height=300>
</applet>
*/
public class ColorDemo extends Applet {
public void init() {
setBackground(Color.CYAN);
}
public void paint(Graphics g) {
g.setColor(Color.red); // predefined color
g.drawRect(50, 100, 150, 100); // rectangle outline is red color
Color clr = new Color(200, 100, 150);
g.setColor(clr);
ET
C
SV
Fonts in Java
The Font class states fonts, which are used to render text in a visible way.
Font class constructor
Font(Font font) //Creates a new Font from the specified font.
Font(String name, int style, int size) //Creates a new Font from the specified name, style
and point size.
Font variables available in Font class are:
Font.BOLD Font. SANS_SERIF
Font.ITALIC Font. CENTER_BASELINE
Font. PLAIN Font. DIALOG
Font. MONOSPACED Font. SERIF
Font. TRUETYPE_FONT Font. TYPE1_FONT
int size int style
float pointSize String name
Some of the commonly used methods supported by the Font class are as follows.
Method Description
String getFamily() Returns the family name of this Font.
int getStyle() Returns the style of this Font.
boolean isBold() Indicates whether or not this Font object’s style is BOLD
boolean isItalic() Indicates whether or not this Font object’s style is ITALIC.
boolean isPlain() Indicates whether or not this Font object’s style is PLAIN.
static Font getFont(String nm) Returns a Font object fom the system properties list.
static Font decode(String str) Returns the Font that the str argument describes.
String toString() Converts this Font object to a String representation.
Example:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
ET
/* <APPLET CODE =”FontDemo.class” WIDTH=300 HEIGHT=200> </APPLET> */
public class FontDemo extends java.applet.Applet
{
C
Font f;
String m;
SV
g.setFont(plainFont);
g.drawString(“Font in PLAIN”, 50, 70);
Font italicFont = new Font(“Serif”, Font.ITALIC, 24);
g.setFont(italicFont);
g.drawString(“Font in ITALIC”, 50, 120);
Font boldFont = new Font(“Serif”, Font.BOLD, 24);
g.setFont(boldFont);
g.drawString(“Font in BOLD”, 50, 170);
Font boldItalicFont = new Font(“Serif”, Font.BOLD+Font.ITALIC, 24);
g.setFont(boldItalicFont);
g.drawString(“Font in BOLD ITALIC”, 50, 220);
}
ET
}
Sample Output:
C
SV
Images in Java
Image control is superclass for all image classes representing graphical images.
Image class constructor
Image() // create an Image object
Some of the commonly used methods supported by the Image class are as follows.
Method Description
Graphics getGraphics() Creates a graphics context for drawing to an off-
screen image.
int getHeight(ImageObserver observer) Determines the height of the image.
Image getScaledInstance(int width, int Creates a scaled version of this image.
height, int hints)
ImageProducer getSource() Gets the object that produces the pixels for the
image.
int getWidth(ImageObserver observer) Determines the width of the image.
The java.applet.Applet class provides following methods to access image.
1. getImage() method that returns the object of Image. Its syntax is as follows.
public Image getImage(URL u, String image){}
ET
2. getDocumentBase() method returns the URL of the document in which applet is em-
bedded.
public URL getDocumentBase(){}
3. URL getCodeBase() method returns the base URL.
C
public URL getCodeBase()
Example:
SV
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
/* <APPLET CODE =”ImageDemo.class” WIDTH=300 HEIGHT=200> </APPLET> */
public class ImageDemo extends java.applet.Applet
{
Image img;
public void init()
{
}
public void paint(Graphics g)
{
ET
C
SV
Event Handling
Any change in the state of any object is called event. For Example: Pressing a button, en-
tering a character in Textbox, Clicking or dragging a mouse, etc. The three main components
in event handling are:
• Events: An event is a change in state of an object. For example, mouseClicked,
mousePressed.
• Events Source: Event source is an object that generates an event. Example: a button,
frame, textfield.
• Listeners: A listener is an object that listens to the event. A listener gets notified when
an event occurs. When listener receives an event, it process it and then return. Listeners
are group of interfaces and are defined in java.awt.event package. Each component
has its own listener. For example MouseListener handles all MouseEvent.
Some of the event classes and Listener interfaces are listed below.
Event Classes Generated when Listener Interfaces
ActionEvent button is pressed, menu-item is selected, Action Listener
list-item is double clicked
MouseEvent mouse is dragged, moved, clicked, pressed Mouse Listener and
or released and also when it enters or exit Mouse Motion
a component Listener
MouseWheelEvent mouse wheel is moved Mouse Wheel Listener
KeyEvent input is received from keyboard Key Listener
ItemEvent check-box or list item is clicked Item Listener
TextEvent value of textarea or textfield is changed Text Listener
AdjustmentEvent scroll bar is manipulated Adjustment Listener
WindowEvent window is activated, deactivated, deico- Window Listener
nified, iconified, opened or closed
ComponentEvent component is hidden, moved, resized or Component Listener
ET
set visible
ContainerEvent component is added or removed from Container Listener
container
FocusEvent component gains or losses keyboard Focus Listener
C
focus
Java program for handling keyboard events.
SV
Test.java
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
//Implementing KeyListener interface to handle keyboard events
public class Test extends Applet implements KeyListener
{
String msg=””;
public void init()
{
addKeyListener(this); //use keyListener to monitor key events
}
public void keyPressed(KeyEvent k) // invoked when any key is pressed down
{
showStatus(“KeyPressed”);
}
public void keyReleased(KeyEvent k) // invoked when key is released
{
showStatus(“KeyRealesed”);
}
//keyTyped event is called first followed by key pressed or key released event
public void keyTyped(KeyEvent k) //invoked when a textual key is pressed
{
ET
msg = msg+k.getKeyChar();
repaint();
}
C
public void paint(Graphics g)
{
SV
Sample Output:
Adapter Classes
ET
An adapter class provides the default implementation of all methods in an event listener
interface. Adapter classes are very useful when you want to process only few of the events
that are handled by a particular event listener interface. For example MouseAdapter provides
empty implementation of MouseListener interface. It is useful because very often you do not
C
really use all methods declared by interface, so implementing the interface directly is very
lengthy.
SV
• Adapter class is a simple java class that implements an interface with only EMPTY
implementation.
• Instead of implementing interface if we extends Adapter class ,we provide
implementation only for require method
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.
event packages. The Adapter classes with their corresponding listener interfaces are as fol-
lows.
Adapter Class Listener Interface
Window Adapter Window Listener
Key Adapter Key Listener
Mouse Adapter Mouse Listener
Mouse Motion Adapter Mouse Motion Listener
Focus Adapter Focus Listener
Component Adapter Component Listener
Container Adapter Container Listener
HierarchyBoundsAdapter HierarchyBoundsListener
Example:
import java.awt.*;
import java.awt.event.*;
public class AdapterExample{
Frame f;
AdapterExample(){
f=new Frame(“Window Adapter”);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
ET
f.setSize(400,400);
f.setLayout(null);
C
f.setVisible(true);
}
SV
Actions
The Java Action interface and AbstractAction class are terrific ways of encapsulating be-
haviors (logic), especially when an action can be triggered from more than one place in your
Java/Swing application.
javax.swing
Interface Action
An Action can be used to separate functionality and state from a component. For example,
if you have two or more components that perform the same function, consider using an Ac-
tion object to implement the function.
An Action object is an action listener that provides not only action-event handling, but
also centralized handling of the state of action-event-firing components such as tool bar but-
tons, menu items, common buttons, and text fields. The state that an action can handle in-
cludes text, icon, mnemonic, enabled, and selected status.
The most common way an action event can be triggered from multiple places in a Java/
ET
Swing application is through the Java menubar (JMenuBar) and toolbar (JToolBar)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
C
import javax.swing.JFrame;
public class ButtonAction {
SV
frame1.pack();
frame1.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
Output:
ET
C
SV
MouseEvent:
An event which indicates that a mouse action occurred in a component. A mouse action
is considered to occur in a particular component if and only if the mouse cursor is over the
unobscured part of the component’s bounds when the action happens. For lightweight com-
ponents, such as Swing’s components, mouse events are only dispatched to the component if
the mouse event type has been enabled on the component.
A mouse event type is enabled by adding the appropriate mouse-based EventListener to
the component (Mouse Listener or Mouse Motion Listener), or by invoking Component.en-
ableEvents (long) with the appropriate mask parameter
(AWTEvent.MOUSE_EVENT_MASK or AWTEvent.MOUSE_MOTION_EVENT_
MASK).
If the mouse event type has not been enabled on the component, the corresponding mouse
events are dispatched to the first ancestor that has enabled the mouse event type.Iif a MouseLis-
tener has been added to a component, or enableEvents(AWTEvent.MOUSE_EVENT_MASK) has
been invoked, then all the events defined by MouseListener are dispatched to the component.
On the other hand, if MouseMotionListener has not been added and enableEvents has not
been invoked with AWTEvent.MOUSE_MOTION_EVENT_MASK, then mouse motion events
are not dispatched to the component. Instead the mouse motion events are dispatched to the
first ancestor that has enabled mouse motion events.
The hierarchy of MouseEvent class is shown below.
ET
C
SV
id modifiers button
MOUSE_PRESSED: BUTTON1_MASK BUTTON1
MOUSE_PRESSED: BUTTON2_MASK BUTTON2
MOUSE_RELEASED: BUTTON1_MASK BUTTON1
MOUSE_CLICKED: BUTTON1_MASK BUTTON1
MOUSE_RELEASED: BUTTON2_MASK BUTTON2
MOUSE_CLICKED: BUTTON2_MASK BUTTON2
If button 2 is released first, the MOUSE_RELEASED/MOUSE_CLICKED pair for BUT-
TON2_MASK arrives first, followed by the pair for BUTTON1_MASK.
MOUSE_DRAGGED events are delivered to the Component in which the mouse button
was pressed until the mouse button is released (regardless of whether the mouse position is
within the bounds of the Component). Due to platform-dependent Drag&Drop implementa-
tions, MOUSE_DRAGGED events may not be delivered during a native Drag&Drop opera-
tion.
In a multi-screen environment mouse drag events are delivered to the Component even
if the mouse position is outside the bounds of the Graphics Configuration associated with
that Component. However, the reported position for mouse drag events in this case may differ
from the actual mouse position:
• In a multi-screen environment without a virtual device: The reported coordinates for mouse
drag events are clipped to fit within the bounds of the GraphicsConfiguration associated
with the Component.
• In a multi-screen environment with a virtual device: The reported coordinates for
mouse drag events are clipped to fit within the bounds of the virtual device associated
with the Component.
The following program is an example for MouseEvent.
import java.awt.*;
import java.awt.event.*;
pubic class MouseListenerExample extends Frame implements MouseListener{
ET
Label l;
MouseListenerExample(){
addMouseListener(this);
C
l=new Label();
l.setBounds(20,50,100,20);
SV
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText(“Mouse Clicked”);
}
public void mouseEntered(MouseEvent e) {
l.setText(“Mouse Entered”);
}
public void mouseExited(MouseEvent e) {
l.setText(“Mouse Exited”);
}
public void mousePressed(MouseEvent e) {
l.setText(“Mouse Pressed”);
}
public void mouseReleased(MouseEvent e) {
l.setText(“Mouse Released”);
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Output:
ET
C
SV
ET
C
Container
The Container is a component in AWT that can contain another component like buttons,
textfields, labels etc. The classes that extend Container class are known as container such as
SV
First(){
SV
Output:
ET
Example program using by creating the object of Frame class (association)
import java.awt.*;
C
class First2{
First2(){
SV
Output:
ET
Java Swing
C
Swing was developed to provide a more sophisticated set of GUI components than the
earlier Abstract Window Toolkit (AWT). Swing provides a look and feel that emulates the
look and feel of several platforms, and also supports a pluggable look and feel that allows ap-
SV
plications to have a look and feel unrelated to the underlying platform. It has more powerful
and flexible components than AWT.
In addition to familiar components such as buttons, check boxes and labels, Swing pro-
vides several advanced components such as tabbed panel, scroll panes, trees, tables, and
lists.
Unlike AWT components, Swing components are not implemented by platform-specific
code. Instead, they are written entirely in Java and therefore are platform-independent. The
term “lightweight” is used to describe such an element.
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JText-
Field, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Swing Features
• Light Weight - Swing component are independent of native Operating System’s
API as Swing API controls are rendered mostly using pure JAVA code instead of
underlying operating system calls.
• Rich controls - Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colourpicker, table controls
• Highly Customizable - Swing controls can be customized in very easy way as visual
appearance is independent of internal representation.
• Pluggable look-and-feel- SWING based GUI Application look and feel can be
changed at run time based on available values.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
ET
C
SV