Unit-8 Event handling and GUI programming (E-next.in)
Unit-8 Event handling and GUI programming (E-next.in)
2. Running State
An applet achieves the running state when the system calls the start() method.
This occurs as soon as the applet is initialized.
An applet may also start when it is in idle state.
At that time, the start() method is overridden.
It's general form is:
public void start( )
{
//Action to be performed
}
3. Idle State
An applet comes in idle state when its execution has been stopped either implicitly
or explicitly.
An applet is implicitly stopped when we leave the page containing the currently
running applet.
An applet is explicitly stopped when we call stop() method to stop its execution.
It's general form is:
public void stop()
{
//Action to be performed
}
4. Dead State
An applet is in dead state when it has been removed from the memory.
This can be done by using destroy() method.
It's general form is:
public void destroy( )
{
//Action to be performed
}
5. Display State
Apart from the above stages, Java applet also possess paint( ) method.
This method helps in drawing, writing and creating colored backgrounds of the
applet.
It takes an argument of the graphics class.
To use the graphics, it imports the package java.awt.Graphics
It's general form is:
public void paint(Graphics g)
{
//Display Statements
}
importjava.awt.Graphics;
importjava.applet.Applet;
Output:
init(): applet started
start(): applet activated
paint(): applet running
stop(): applet inactivated
destroy(): applet destroyed
Q.4 Explain Event delegation Method? Explain it? Explain ItemListener and Mouselistner
interface.
Q.5 Write Applet program to handle mouse events.
Q.6 What is Adapter class.
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.
1) Event source
An event source is a component, such as a GUI component, that generates an event.
The event source can be generated by any type of user interaction.
You can also combine a number of different types of events into one event object.
For example, if a user clicks and drags an icon, you can sum up the mouse-clicked
event and the mouse-moved event into one event object.
In the event delegation model, a class represents each event type.
Event objects are all defined in the java.util.EventObject subclasses.
Here is the general form:
public void addTypeListener(TypeListener el)
2) Event listener
It is also known as event handler.
Listener is responsible for generating response to an event.
From java implementation point of view the listener is also an object.
Event listeners are objects that receive notification of an event.
Listener waits until it receives an event. Once the event is received, the listener
process the event an then returns.
To receive notification of an event, the object must be registered with the event
source. To subscribe to the event source, you implement the appropriate listener
interface.
All listeners are implementations of the Event Listener interface or one of its
subinterfaces.
The Java API provides a predefined listener interface for each set of event types that
a source can fire.
For example, the MouseListenerinterface deals with mouse events, and the
ActionListener interface deals with action events fired by buttons and other
components.
3) Adapter
Adapters are abstract classes that implement listener interfaces using predefined
methods. These are provided for convenience.
You can use an adapter to apply one listener's methods without having to implement
all other methods.
Adapters provide empty implementations for all interfaces' methods, so you only
need to override the method you are interested in.
Advantages
It is simple and well suited to an object-oriented programming environment.
Disadvantages
An event can only be handled by the component from which it originated or by one
of the containers of the originating component.
In order to handle events, you must either subclass the component that receives the
event or create a handleEvent() method at the base container.
itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or
unclick on the registered checkbox component.
public abstract void itemStateChanged(ItemEvent e));
Interface declaration
Following is the declaration for java.awt.event.ItemListener
interface public interface ItemListener extends EventListener
Methods inherited
This interface inherits methods from the following interfaces: java.awt.EventListener
public ChoiceAction()
{
setTitle("Choice with ItemListener Demo"); // Set frame properties
setSize(400,400);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
Output:
Interface Declaration
Following is the declaration for java.awt.event.MouseListener interface:
public interface MouseListener extends EventListener
Methods Inherited
This interface inherits methods from the following interfaces: java.awt.EventListener
MouseListenerExample()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
Q.7 State the five Layouts in Layout Manager for Java AWT. Show the layouts displayed by
each of these Layout.
Q.8 What is Layout? Explain diffrent types of layout manager in detail?
Q.9 Write a short note on BorderLyout and GridLayout.
Layout
Layout means the arrangement of components within the container.
In other way we can say that placing the components at a particular position within
the container.
The task of layouting the controls is done automatically by the Layout Manager.
Layout Manager
The layout manager automatically positions all the components within the container.
If we do not use layout manager then also the components are positioned by the
default layout manager.
It is possible to layout the controls by hand but it becomes very difficult because of
the following two reasons.
It is very tedious to handle a large number of controls within the container.
Oftenly the width and height information of a component is not given when we need
to arrange them.
Java provide us with various layout manager to position the controls. The properties
like size, shape and arrangement varies from one layout manager to other layout
manager.
When the size of the applet or the application window changes the size, shape and
arrangement of the components also changes in response i.e. the layout managers
adapt to the dimensions of applet viewer or the application window.
The layout manager is associated with every Container object. Each layout manager
is an object of the class that implements the LayoutManager interface.
Java LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers.
There are following AWT and Swing classes that represents the layout managers:
1) java.awt.BorderLayout
2) java.awt.FlowLayout
3) java.awt.GridLayout
4) java.awt.CardLayout
5) java.awt.GridBagLayout
6) javax.swing.BoxLayout
7) javax.swing.GroupLayout
8) javax.swing.ScrollPaneLayout
9) javax.swing.SpringLayout etc.
1. Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south,
east, west and center.
Each region (area) may contain one component only.
It is the default layout of frame or window.
import java.awt.*;
import javax.swing.*;
Border()
{
f=new JFrame();
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);
}
Output:
2. Java GridLayout
The GridLayout is used to arrange the components in rectangular grid.
One component is displayed in each rectangle.
import java.awt.*;
import javax.swing.*;
MyGridLayout()
{
f=new JFrame();
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.setSize(300,300);
f.setVisible(true);
}
3. Java 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.*;
import javax.swing.*;
MyFlowLayout()
{
f=new JFrame();
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyFlowLayout();
}
}
Output:
4. Java BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally.
For this purpose, BoxLayout provides four constants. They are as follows:
Fields of BoxLayout class
1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS
import java.awt.*;
import javax.swing.*;
public BoxLayoutExample1 ()
{
buttons = new Button [5];
for (int i = 0;i<5;i++)
{
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setSize(400,400);
setVisible(true);
}
Output:
import java.awt.*;
import javax.swing.*;
public BoxLayoutExample2()
{
buttons = new Button [5];
for (int i = 0;i<5;i++)
{
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
BoxLayoutExample2 b=new BoxLayoutExample2();
}
}
Output:
5. Java CardLayout
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.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample()
{
c=getContentPane();
card=new CardLayout(40,30); //create 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);
}
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
Swing components
1. JButton
JButton class provides functionality of a button.
JButton class has three constuctors,
1. JButton(Icon ic)
2. JButton(String str)
3. JButton(String str, Icon ic)
It allows a button to be created using icon, a string or both.
JButton supports ActionEvent.
When a button is pressed an ActionEvent is generated.
Output:
2. JTextField
JTextField is used for taking input of single line of text. It is most widely used text
component.
It has three constructors,
1. JTextField(int cols)
2. JTextField(String str, int cols)
3. JTextField(String str)
cols represent the number of columns in text field.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
3. JCheckBox
JCheckBox class is used to create checkboxes in frame.
Following is constructor for
1. JCheckBox,
2. JCheckBox(String str)
Import javax.swing.*;
Import java.awt.event.*;
Import java.awt.*;
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
Output:
4. JRadioButton
Radio button is a group of related button in which only one can be selected.
JRadioButton class is used to create a radio button in Frames.
Following is the constructor for JRadioButton,
JRadioButton(String str)
importjavax.swing.*;
importjava.awt.event.*;
importjava.awt.*;
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
5. JComboBox
Combo box is a combination of text fields and drop-down list.
JComboBox component is used to create a combo box in Swing.
Following is the constructor for JComboBox,
JComboBox(String arr[])
importjavax.swing.*;
importjava.awt.event.*;
importjava.awt.*;
public Test()
{
JComboBox jc = new JComboBox(name); //initialzing combo box with list of name.
add(jc); //adding JComboBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
Output:
Q.11 Write a program to create a Web based GUI application for student registration form
using swing.
Q.12 Write a program to create a GUI by using any five controls of AWT.
jp1.add (lna);
jp1.add (tname);
jp1.add (ladd);
jp1.add (tadd);
jp2.add (lgender);
jp2.add (rm);
jp2.add (rf);
jp3.setLayout(new GridLayout(2,3));
jp3.add (los);
jp3.add (cb1);
jp3.add (cb2);
jp3.add (cb3);
jp3.add (cb4);
jp4.add (llang);
jp4.add (sb1, BorderLayout.NORTH);
jp4.add (bok);
jp4.add (bclear);
jp6.add (jp1);
jp6.add (jp2);
jp6.add (jp3);
jp6.add (jp4);
jp6.add (jp5);
jf.add (jp6);
jf.setDeafaultCloseOperation (jf.EXIT_ON_CLOSE);
jf.setSize (350, 400);
jjf.setVisible (true);
}
Output:
Q.13 Write an applet program that will show GUI components like line, ellipse, polygon,
etc.
1. Applet Line Program:
//Drawing Lines
import java.awt.*;
import java.applet.*;
/*
<applet code="Lines" width=300 Height=250>
</applet>
*/
Output:
import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangle" width=300 Height=300>
</applet>
*/
Output:
*/
import java.awt.*;
import java.applet.*;
/*
Output:
*/
import java.awt.*;
import java.applet.*;
/*
Output:
*/
import java.awt.*;
import java.applet.*;
/*
<applet code="Polygon" width=300 Height=300>
</applet>
*/
Output: