Vayu Sena
Vayu Sena
What is an Event?
Change in the state of an object is known as event i.e. event describes the
change in state of source. Events are generated as result of user interaction
with the graphical user interface components. For example, clicking on a
button, moving the mouse, entering a character through keyboard,selecting
an item from list, scrolling the page are the activities that causes an event
to happen.
Types of Event
The events can be broadly classified into two categories:
Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or
software failure, timer expires, an operation completion are the example of
background events.
The Delegation Event Model has the following key participants namely:
The benefit of this approach is that the user interface logic is completely
separated from the logic that generates the event. The user interface
element is able to delegate the processing of an event to the separate piece
of code. In this model ,Listener needs to be registered with the source
object so that the listener can receive the event notification. This is an
efficient way of handling the event because the event notifications are sent
only to those listener that want to receive them.
If you do not implement the any if the predefined interfaces then your class can
not act as a listener class for a source object.
Callback Methods
These are the methods that are provided by API provider and are defined
by the application programmer and invoked by the application developer.
Here the callback methods represents an event method. In response to an
event java jre will fire callback method. All such callback methods are
provided in listener interfaces.
If a component wants some listener will listen to it's events the the source
must register itself to the listener.
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on
button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
1. Within class
2. Other class
3. Anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
public void setBounds(int xaxis, int yaxis, int width, int height); have
been used in the above example that sets the position of the component it may
be button, textfield etc.
2) Java event handling by outer class
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
new AEvent3();
}
}
AWT Adapters:
Following is the list of commonly used adapters while listening GUI events
in AWT.
1 FocusAdapter
2 KeyAdapter
3 MouseAdapter
4 MouseMotionAdapter
5 WindowAdapter
Class constructors
S.N. Constructor & Description
1 FocusAdapter()
Class methods
S.N. Method & Description
1 void focusGained(FocusEvent e)
2 focusLost(FocusEvent e)
Methods inherited
This class inherits methods from the following classes:
java.lang.Object
FocusAdapter Example
Create the following java program using any editor of your choice in
say D:/ > AWT > com > tutorialspoint > gui >
AwtAdapterDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public AwtAdapterDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
cancelButton.addFocusListener(new FocusAdapter(){
public void focusLost(FocusEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName()
+ " lost focus. ");
}
});
controlPanel.add(okButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
}
Java Inner Classes
Java inner class or nested class is a class which is declared inside the class
or interface.
We use inner classes to logically group classes and interfaces in one place
so that it can be more readable and maintainable.
Additionally, it can access all the members of outer class including private
data members and methods.
There are basically three advantages of inner classes in java. They are as
follows:
Nested classes represent a special type of relationship that is it can
access all the members (data members and methods) of outer
class including private.
Inner class is a part of nested class. Non-static nested classes are known as
inner classes.
Type Description
Syntax:
class Outer{
//code
class Inner{
//code
}
}
Java Member inner class example
In this example, we are creating msg() method in member inner class that
is accessing the private data member of outer class.
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output:
data is 30
Java Anonymous inner class
A class that have no name is known as anonymous inner class in java. It
should be used if you have to override method of class or interface. Java
Anonymous inner class can be created by two ways:
Interface
Output:
nice fruits
Output:
30
data is 30
In this example, you need to create the instance of static nested class
because it has instance method msg(). But you don't need to create the
object of Outer class because nested class is static and static properties,
methods or classes can be accessed without object.
Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can
have other components like button, textfield etc.
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int sets the size (width and height) of the component.
height)
public void defines the layout manager for the component.
setLayout(LayoutManager m)
public void setVisible(boolean status) changes the visibility of the component, by default
false.
To create simple awt example, you need a frame. There are two ways to create a
frame in AWT.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we
are showing Button component on the Frame.
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[])
{
First f=new First();
}
}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above
example that sets the position of the awt button.
AWT Example by Association
Let's see a simple example of AWT where we are creating instance of Frame class.
Here, we are showing Button component on the Frame.
import java.awt.*;
class First2
{
First2()
{
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
First2 f=new First2();
}
}
The object of Label class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but
a user cannot edit it directly.
Output:
The button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.
Output:
Output:
Output:
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice selected
by user is shown on the top of a menu. It inherits Component class.
Output:
The object of a TextField class is a text component that allows the editing of a single
line text. It inherits TextComponent class.
Output:
The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and
columns.
Output:
Output:
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The items
used in a menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the
menu bar. It inherits the MenuItem class.
Output:
Java AWT Canvas
The Canvas control represents a blank rectangular area where the application can
draw or trap input events from the user. It inherits the Component class.
Output:
Layouts
Flow Layout, Grid Layout, Border Layout, Card Layout.
Java LayoutManagers
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
Java BorderLayout
import java.awt.*;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
Border b = new Border();
}
}
Output:
GridLayout
Example:
import java.awt.*;
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
MyGridLayout m=new MyGridLayout();
}
}
Output:
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another
(in a flow). It is the default layout of applet or panel.
import java.awt.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
MyFlowLayout m=new MyFlowLayout();
}
}
CardLayout
The CardLayout class manages the components in such a way that only one
component is visible at a time. It treats each component as a card in the
container. Only one card is visible at a time, and the container acts as a stack
of cards. The first component added to a CardLayout object is the visible
component when the container is first displayed.
The CardLayout class manages the components in such a manner that only
one component is visible at a time. It treats each component as a card that is
why it is known as CardLayout.
Constructors of CardLayout class
1. CardLayout(): creates a card layout with zero horizontal and vertical
gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
}