B.Sc-III NEP JAVA UNIT-4
B.Sc-III NEP JAVA UNIT-4
Event: Changing the state of an object (component) is known as an event. For example, click
on button, dragging mouse etc.
Event: describes the change in state of component. 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 and selecting an item from list.
Def: Event Handling is the mechanism that controls the event and decides what should happen
if an event occurs. This mechanism has the code which is known as event handler that is executed
when an event occurs.
The java.awt.event package provides many event classes and Listener interfaces for event
handling.
Foreground Events
Foreground events are those events that require user interaction to generate. In order to
generate these foreground events, the user interacts with components in GUI. When a user clicks on a
button, moves the cursor, and scrolls the scrollbar, an event will be fired.
Background Events
Background events don't require any user interaction. These events automatically generate in
the background. OS failure, OS interrupts, operation completion, etc., are examples of background
events.
In Java, MouseListener is a class that gets notified when there is a change in the mouse state.
Changes of the mouse can be pressing, clicking, and releasing it. It can also be entering or exiting the
window area. Mouselistener is working with the help of keyword implements and this listener
interface can be gained from the java.awt.event package. More details on it will be explained in the
following sections.
MouseMotionListener
The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified against
MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It has two
methods.
A KeyEvent is generated when keyboard input occurs. There are three types of key events,
which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and
KEY_TYPED.
The first two events are generated when any key is pressed or released. The last event occurs
only when a character is generated. Remember, not all keypresses result in characters. For example,
pressing shift does not generate a character. On entering the character the Key event is generated.
There are three types of key events which are represented by the integer constants.
Interface declaration
ABSTRACT WINDOW TOOLKIT (AWT) Java AWT (Abstract Window Toolkit) is an API
to develop GUI or window-based application in java. Java AWT components are platform-dependent
i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its
components uses the resources of system. The Abstract Window Toolkit(AWT) support for applets.
The AWT contains numerous classes and methods that allow you to create and manage windows.
1. Component: All the elements like the button, text fields, scroll bars, etc. are called components. In
Java AWT, there are classes for each component as shown in above diagram. In order to place every
component in a particular position on a screen, we need to add them to a container.Components are
elementary GUI entities, such as Button, Label, and TextField.
2. Container: The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as Frame,
Dialog and Panel.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window :
The window is the container that has 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.
Dialog:
Dialog class is a subclass of Window. It does not have an icon or menu bar. Such a
window is usually called a dialog box.
Panel
The class Panel is the simplest container class. It provides space in which an application can attach
any other component, including other panels. It uses FlowLayout as default layout manager.
Class declaration
Following is the declaration for java.awt.Panel class:
public class Panel
extends Container
implements Accessible
Class constructors
S.N. Constructor & Description
1 Panel()
Creates a new panel using the default .
2 Panel(LayoutManager layout)
Creates a new panel with the specified layout manager.
Class methods
S.N. Method & Description
1 void addNotify()
Creates the Panel's peer.
2 AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Panel.
Frame
The class Frame is a top level window with border and title. It uses BorderLayout as default layout
manager.
Class declaration
Following is the declaration for java.awt.Frame class:
public class Frame
extends Window
implements MenuContainer
Field
Following are the fields for java.awt.Frame class:
static float BOTTOM_ALIGNMENT -- Ease-of-use constant for getAlignmentY.
static int CROSSHAIR_CURSOR -- Deprecated. replaced by
Cursor.CROSSHAIR_CURSOR.
static int DEFAULT_CURSOR -- Deprecated. replaced by Cursor.DEFAULT_CURSOR.
static int E_RESIZE_CURSOR -- Deprecated. replaced by Cursor.E_RESIZE_CURSOR.
static int HAND_CURSOR -- Deprecated. replaced by Cursor.HAND_CURSOR.
static int ICONIFIED -- This state bit indicates that frame is iconified.
static int MAXIMIZED_BOTH -- This state bit mask indicates that frame is fully maximized
(that is both horizontally and vertically).
static int MAXIMIZED_HORIZ -- This state bit indicates that frame is maximized in the
horizontal direction.
static int MAXIMIZED_VERT -- This state bit indicates that frame is maximized in the
vertical direction.
static int MOVE_CURSOR -- Deprecated. replaced by Cursor.MOVE_CURSOR.
static int N_RESIZE_CURSOR -- Deprecated. replaced by Cursor.N_RESIZE_CURSOR.
static int NE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NE_RESIZE_CURSOR.
static int NORMAL -- Frame is in the "normal" state.
static int NW_RESIZE_CURSOR -- Deprecated. replaced by
Cursor.NW_RESIZE_CURSOR.
static int S_RESIZE_CURSOR -- Deprecated. replaced by Cursor.S_RESIZE_CURSOR.
static int SE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SE_RESIZE_CURSOR.
static int SW_RESIZE_CURSOR -- Deprecated. replaced by
Cursor.SW_RESIZE_CURSOR.
static int TEXT_CURSOR -- Deprecated. replaced by Cursor.TEXT_CURSOR.
static int W_RESIZE_CURSOR -- Deprecated. replaced by Cursor.W_RESIZE_CURSOR.
static int WAIT_CURSOR -- Deprecated. replaced by Cursor.WAIT_CURSOR.
Class constructors
S.N. Constructor & Description
1 Frame()
Constructs a new instance of Frame that is initially invisible.
2 Frame(GraphicsConfiguration gc)
Constructs a new, initially invisible Frame with the specified GraphicsConfiguration.
3 Frame(String title)
Constructs a new, initially invisible Frame object with the specified title.
4 Frame(String title, GraphicsConfiguration gc)
Constructs a new, initially invisible Frame object with the specified title and a
GraphicsConfiguration.
Class methods
S.N. Method & Description
1 void addNotify()
Makes this Frame displayable by connecting it to a native screen resource.
2 AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Frame.
3 int getCursorType()
Deprecated. As of JDK version 1.1, replaced by Component.getCursor().
4 int getExtendedState()
Gets the state of this frame.
5 static Frame[] getFrames()
Returns an array of all Frames created by this application.
6 Image getIconImage()
Returns the image to be displayed as the icon for this frame.
7 Rectangle getMaximizedBounds()
Gets maximized bounds for this frame.
8 MenuBar getMenuBar()
Gets the menu bar for this frame.
9 int getState()
Gets the state of this frame (obsolete).
10 String getTitle()
Gets the title of the frame.
11 boolean isResizable()
Indicates whether this frame is resizable by the user.
12 boolean isUndecorated()
Indicates whether this frame is undecorated.
13 protected String paramString()
Returns a string representing the state of this Frame.
14 void remove(MenuComponent m)
Removes the specified menu bar from this frame.
15 void removeNotify()
Makes this Frame undisplayable by removing its connection to its native screen resource.
16 void setCursor(int cursorType)
Deprecated. As of JDK version 1.1, replaced by Component.setCursor(Cursor).
17 void setExtendedState(int state)
Sets the state of this frame.
18 void setIconImage(Image image)
Sets the image to be displayed as the icon for this window.
19 void setMaximizedBounds(Rectangle bounds)
Sets the maximized bounds for this frame.
20 void setMenuBar(MenuBar mb)
Sets the menu bar for this frame to the specified menu bar.
21 void setResizable(boolean resizable)
Sets whether this frame is resizable by the user.
22 void setState(int state)
Sets the state of this frame (obsolete).
23 void setTitle(String title)
Sets the title for this frame to the specified string.
24 void setUndecorated(boolean undecorated)
Disables or enables decorations for this frame.
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
LayoutManager is an interface that is implemented by all the classes of layout managers. There are the
following classes that represent 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.
Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.
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 a frame or
window. The BorderLayout provides five constants for each region:
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
3) AWT doesn't support pluggable look and Swing supports pluggable look
feel. and feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of
desktop applications.
Hierarchy of Java Swing classes
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed. It inherits AbstractButton class.
Methods Description
Java JLabel
The object of JLabel 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. It
inherits JComponent class.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,image,
horizontalAlignment) and horizontal alignment.
Output:
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking
on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.
Java JTextField
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
Commonly used Methods:
Methods Description
JComboBox
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 JComponent class. A list displays a series of items from which
the user may select one or more items Lists are created with class JList, which directly extends class
JComponent.
JComboBox class declaration
The JRadioButton class is used to create a radio button. It is used to choose one option frommultiple
options. It is widely used in exam systems or quiz. It should be added in ButtonGroup to select one radio
button only.
JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.
JList(ary[] listData) Creates a JList that displays the elements in the specifiedarray.
Java JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any other
component. It inherits the JComponents class.It doesn't have title bar.
Constructor Description
JSlider(int min, int max) creates a horizontal slider using the given minand max.
JSlider(int min, int max, int creates a horizontal slider using the given min, max and
value) value.
JSlider(int orientation, int min, int creates a slider using the given orientation, min, max
max, int value) and value.
Method Description
The JMenuBar class is used to display menubar on the window orframe. It may
have several menus.
The object of JMenu class is a pull down menu component which isdisplayed
from the menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a
menu must belong to the JMenuItem or any of its subclass.
JMenuBar class declaration
public class JMenuBar extends JComponent implements MenuElement,Accessible
import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample()
{
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBarmb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
OUTPUT:
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It
runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the
subclass of Component.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can
be used for drawing oval, rectangle, arc etc.
To execute the applet by html file, create an applet and compile it. After that create an html file and place
the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}