0% found this document useful (0 votes)
144 views32 pages

B.Sc-III NEP JAVA UNIT-4

The document discusses event handling in Java GUI programming. It defines events as changes in state of GUI components like buttons that are triggered by user interactions. It explains that event handling uses listener interfaces like ActionListener, MouseListener and KeyListener to define code that responds to events. The document also categorizes events as foreground, triggered by direct user interaction, or background from other sources. It provides examples of commonly used event classes and their associated listener interfaces and event handling methods.

Uploaded by

kalpanac8090
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
144 views32 pages

B.Sc-III NEP JAVA UNIT-4

The document discusses event handling in Java GUI programming. It defines events as changes in state of GUI components like buttons that are triggered by user interactions. It explains that event handling uses listener interfaces like ActionListener, MouseListener and KeyListener to define code that responds to events. The document also categorizes events as foreground, triggered by direct user interaction, or background from other sources. It provides examples of commonly used event classes and their associated listener interfaces and event handling methods.

Uploaded by

kalpanac8090
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Event and GUI Programming

Event handling in Java:

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.

Event Classes Description Listener Interface


Generated when button is pressed, menu-item is
ActionEvent ActionListener
selected, list-item is double clicked
Generated when mouse is dragged, moved,
MouseEvent clicked, pressed or released and also when it MouseListener
enters or exit a component
KeyEvent Generated when input is received from keyboard KeyListener
ItemEvent Generated when check-box or list item is clicked ItemListener
Generated when value of textarea or textfield is
TextEvent TextListener
changed
MouseWheelEvent Generated when mouse wheel is moved MouseWheelListener

Types of events in Java


Java provides a package java.awt.event that contains several event classes.

We can classify the events in the following two categories:


1. Foreground Events
2. Background Events

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.

These are some of the most used Event classes:


S.
Event Class Listener Interface Methods Descriptions
No.
ActionEvent
indicates that a
1. ActionEvent ActionListener actionPerformed()
component-defined
action occurred.
Adjustment events
occur by an
2. AdjustmentEvent AdjustmentListener adjustmentValueChanged()
adjustable object like
a scrollbar.
An event occurs
componentResized(),
when a component
componentMoved(),
3. ComponentEvent ComponentListener moved, changed its
componentShown() and
visibility or the size
componentHidden()
changed.
The event is fired
componentRemoved() and when a component is
4. ContainerEvent ContainerListener
componentAdded() added or removed
from a container.
Focus events include
focusLost() and
5. FocusEvent FocusListener focus, focusout,
focusGained()
focusin, and blur.
Item event occurs
6. ItemEvent ItemListener itemStateChanged() when an item is
selected.
A key event occurs
keyPressed(),
when the user presses
7. KeyEvent KeyListener keyReleased(), and
a key on the
keyTyped().
keyboard.
mouseClicked(),
mousePressed(),
mouseEntered(),
mouseExited() and A mouse event
MouseListener and mouseReleased() are the occurs when the user
8. MouseEvent
MouseMotionListener mouseListener methods. interacts with the
mouseDregged() and mouse.
mouseMoved() are the
MouseMotionListener()
methods.
MouseWheelEvent
occurs when the
9. MouseWheelEvent MouseWheelListener mouseWheelMoved().
mouse wheel rotates
in a component.
TextEvent TextListener textChanged() TextEvent occurs
10. when an object's text
change.
WindowEvent WindowListener windowActivated(), Window events
windowDeactivated(), occur when a
windowOpened(), window's status is
11. windowClosed(), changed.
windowClosing(),
windowIconfied() and
windowDeiconified().
Introduction to Java MouseListener & Mouse Motion Listener

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.

Declaration: Java MouseListener interface can be declared using the following


syntax. Public interface MouseListener extends EventListener

Methods of Java MouseListener


There are five methods. They are :

1. mouseClicked(MouseEventev): This method will get invoked when a Mouse button is


clicked on a component.
2. mouseEntered(MouseEventev): This method will get invoked when a Mouse is entering a
component.
3. mouseExited(MouseEventev): This method will get invoked when a Mouse is exiting a
component.
4. mousePressed(MouseEventev): This method will get invoked when a Mouse button is
pressed on a component.
5. mouseReleased(MouseEventev): This method will get invoked when a Mouse button is
released on a component.

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.

Methods of MouseMotionListener interface

public abstract void mouseDragged(MouseEvent e);


public abstract void mouseMoved(MouseEvent e);
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three
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.

These key events are following Class


KEY_PRESSED
KEY_RELASED
KEY_TYPED

Interface declaration

Following is the declaration for java.awt.event.KeyListener interface:

public interface KeyListener extends EventListener

Methods of KeyListener interface


The signature of 3 methods found in KeyListener interface are given below:

Sr. no. Method name Description


1. public abstract void keyPressed (KeyEvent e); It is invoked when a key has been
pressed.
2. public abstract void keyReleased (KeyEvent e); It is invoked when a key has been
released.
3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been
typed.
GUI Basics (GUI PROGRAMMING WITH JAVA)

A GUI components is an Object that represents a screen element such as a button or a


text field. A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an
application. A GUI gives an application to a distinctive “look and-feel.
GUI (Graphical User Interface): In GUI user interacts with the application through
graphics. GUI is user friendly. GUI makes application attractive. It is possible to simulate real object
in GUI programs. In java to write GUI programs we can use awt (Abstract Window Toolkit) package.
Java provides a large library of graphical user interface components. The javax.swing package
provides several classes using to create graphical user interfaces. The basic steps of creating and
displaying an interface are as follows:
 Create a JFrame object. A frame component handles basic windowing
functionality, for example closing.
 Create one or more JPanel objects. A panel is like a window pane. It is a container that
can hold other elements.
 Add elements to your panel. The swing library provides several types of elements
including buttons, labels, and text boxes.
 Add your panel to the frame.
 Resize everything.
 Make the frame visible.

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.

The java.awt package provides classes for AWT api such as


TextField,
Label,
TextArea,
RadioButton,
CheckBox,
Choice,
List etc.
AWT Classes
The AWT classes are contained in the java.awt package. It is one of Java's largest packages.
The AWT supports the following types of controls:
1. Labels
2. Push buttons
3. Check boxes
4. Choice lists
5. Lists
6. Scroll bars
7. Text editing

Components and Containers in AWT:


There are two types of GUI elements/class:

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.

Java AWT Class Hierarchy

The hierarchy of Java AWT classes is given below.

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.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal
and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and
the given horizontal and vertical gap.
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 a frame or
window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.
Java GridLayout

The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns
but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given
rows and columns along with given horizontal and vertical gaps.
Java Swing Tutorial
Java Swing tutorial 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, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components


are platform-independent.

2) AWT components are heavyweight. Swing components


are lightweight.

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.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and
view.

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

The hierarchy of java swing API is given below.

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.

JButton class declaration

Let's see the declaration for javax.swing.JButton class.

public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:


Constructor Description

JButton() It creates a button with no text and icon.


JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of Abstract Button class:

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on thebutton.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void It is used to add the action listener to this


addActionListener(ActionListene object.
ra)

Java JButton Example


import javax.swing.*;
public class ButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");JButton
b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b); f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

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 class declaration

Let's see the declaration for javax.swing.JLabel class.


 public class JLabel extends JComponent implements SwingConstants,Accessible
Commonly used Constructors:
Constructor Description

JLabel() Creates a JLabel instance with no image andwith an


empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specifiedimage.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,image,
horizontalAlignment) and horizontal alignment.

Commonly used Methods:


Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this


component will display.

void setHorizontalAlignment(int It sets the alignment of the label's contentsalong


alignment) the X axis.
Icon getIcon() It returns the graphic image that the labeldisplays.

int getHorizontalAlignment() It returns the alignment of the label's contentsalong


the X axis.

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.

JCheckBox class declaration

Let's see the declaration for javax.swing.JCheckBox class.

public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:


Constructor Description

JJCheckBox() Creates an initially unselected check box buttonwith no


text, no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, Creates a check box with text and specifieswhether or


boolean selected) not it is initially selected.

JCheckBox(Action a) Creates a check box where properties are takenfrom


the Action supplied.
Commonly used Methods:
Methods Description

AccessibleContext It is used to get the AccessibleContext associated


getAccessibleContext( with this JCheckBox.
)

protected String paramString() It returns a string representation of this JCheckBox.

Java JTextField

The object of a JTextField class is a text component that allows theediting


of a single line text. It inherits JTextComponent class.

JTextField class declaration

Let's see the declaration for javax.swing.JTextField class.


 public class JTextField extends JTextComponent implements Swing
Constants

Commonly used Constructors:


Constructor Description

JTextField() Creates a new TextField

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

void addActionListener(ActionListener l) It is used to add the specified action listener to


receive action events from this textfield.

Action getAction() It returns the currently set Action for this


ActionEvent source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void removeActionListener(ActionListener l) It is used to remove the specified action listener so


that it no longer receives action events from this
textfield.

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

Let's see the declaration for javax.swing.JComboBox class.


 public class JComboBox extends JComponent implements ItemSelectab
le, ListDataListener, ActionListener, Accessible

Commonly used Constructors:


Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[]items) Creates a JComboBox that contains the elements inthe


specified array.

JComboBox(Vector<?> Creates a JComboBox that contains the elements inthe


items) specified Vector.

Commonly used Methods:


Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from thelist.

void setEditable(boolean b) It is used to determine whether the


JComboBox is editable.
Java JRadioButton

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 class declaration

Let's see the declaration for javax.swing.JRadioButton class.

1. public class JRadioButton extends JToggleButton implements Accessible


Commonly used Constructors:
Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified


text.

JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.

Commonly used Methods:


Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on thebutton.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener It is used to add the action listener to this


a) object.
Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class. A combo box (sometimes
called a drop-down list)enables the user to select one item from a list

JList class declaration

Let's see the declaration for javax.swing.JList class.


 public class JList extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specifiedarray.

JList(ListModel<ary>dataModel) Creates a JList that displays elements from the specified,non-null,


model.

Commonly used Methods:


Methods Description

Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be


listener) notified each time a change to the selection
occurs.

int getSelectedIndex() It is used to return the smallest


selected cell index.
ListModel getModel() It is used to return the data model that holds a
list of items displayed by the JList
component.

void setListData(Object[] listData) It is used to create a read-only


ListModel from an array of objects.

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.

JPanel class declaration

 public class JPanel extends JComponent implements Accessible


Commonly used Constructors:
Constructor Description

JPanel() It is used to create a new JPanel with a double bufferand a


flow layout.

JPanel(boolean It is used to create a new JPanel with FlowLayout andthe


isDoubleBuffered) specified buffering strategy.

JPanel(LayoutManag It is used to create a new JPanel with the specified layout


er layout) manager.
Jslider in java
Slider is a part of Java Swing package .JSlider is an implementation of slider. The Component allows the user
to select a value by sliding the knob withing the bounded value . The slider can show Major Tick marks and
also the minor tick marks between two major tick marks, The knob can be positioned at only those points.
The following picture shows an application that uses a slider to controlanimation speed.
Class Declaration
Following is the declaration for javax.swing.JSlider class −

public class JSlider extends


JComponent
implements SwingConstants, Accessible

Commonly used Constuctors of JSlider class:

Constructor Description

JSlider() creates a slider with the initial value of 50 andrange of 0


to 100.

JSlider(int orientation) creates a slider with the specified orientation setby


either JSlider.HORIZONTAL or JSlider.VERTICAL
with the range 0 to 100 and initial value 50.

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.

Commonly used Methods of JSlider class:

Method Description

public void is used to set the minor tick spacing to theslider.


setMinorTickSpacing(int n)

public void is used to set the major tick spacing to theslider.


setMajorTickSpacing(int n)

public void is used to determine whether tick marks arepainted.


setPaintTicks(boolean b)

public void is used to determine whether labels are painted.


setPaintLabels(boolean b)
public void is used to determine whether track is painted.
setPaintTracks(boolean b)

menus with frame


menu is a group of commands located in a menubarJMenuBar, JMenu and JMenuItems are a
part of Java Swing package. JMenuBar is an implementation of menu bar . the JMenuBar contains
one or more JMenu objects, when the JMenu objects are selected they display a popup showing one or
more JMenuItems .JMenu basically represents a menu .

Java JMenuBar, JMenu and JMenuItem

 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

JMenu class declaration


public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration


public class JMenuItem extends AbstractButton implements Accessible,
MenuElement

Java JMenuItem and JMenu Example

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.

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:

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

The Component class provides 1 life cycle method of applet.

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.

How to run an Applet?


There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

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);
}
}

You might also like