0% found this document useful (0 votes)
20 views

Java Unit V

Java notes From jntuh

Uploaded by

naninani102112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Java Unit V

Java notes From jntuh

Uploaded by

naninani102112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

UNIT V

GUI PROGRAMMING WITH SWING

INTRODUCTION TO JAVA GUI PROGRAMMING WITH SWING:

Java Swing is a GUI toolkit and a part of JFC (Java Foundation Class) helpful in developing window-
based applications.

Java Swing is lightweight and platform-independent that contains various components and container
classes.

It provides a wide range of components, such as buttons, text fields, and menus, that can be used to create
attractive and functional GUIs.

In Java Swing, there are several components like a scroll bar, button, text field, text area, checkbox, radio
button, etc. These components jointly form a GUI that offers a rich set of functionalities and allows high-
level customization.

What is Java Swing?

Java Swing is a set of graphical user interface (GUI) components that are part of the Java platform.
Swing components are built on top of the Abstract Window Toolkit (AWT), but they provide a number of
advantages over AWT components. For example, Swing components are more lightweight and efficient,
and they are platform-independent.

How to install Java Swing

Java Swing is included in the Java Development Kit (JDK).

To install the JDK, go to the Oracle website and download the latest version of the JDK for your operating
system. Once the JDK is installed, you can start creating Swing GUIs.

Main Features of Swing Toolkit

 Platform Independent
 Customizable
 Extensible
 Configurable
 Lightweight

Swing and JFC

JFC is an abbreviation for Java Foundation classes, which encompass a group of features for
building Graphical User Interfaces(GUI) and adding rich graphical functionalities and interactivity to Java
applications.

Features of JFC

 Swing GUI components.


 Look and Feel support.
 Java 2D.

Introduction to Swing Classes

JPanel : JPanel is Swing's version of AWT class Panel and uses the same default layout, FlowLayout.
JPanel is descended directly from JComponent.

JFrame : JFrame is Swing's version of Frame and is descended directly from Frame class. The component
which is added to the Frame, is refered as its Content.

JWindow : This is Swing's version of Window and hass descended directly from Window class.
Like Window it uses BorderLayout by default.

JLabel : JLabel descended from Jcomponent, and is used to create text labels.

JButton : JButton class provides the functioning of push button. JButton allows an icon, string or both
associated with a button.

JTextField : JTextFields allow editing of a single line of text.

Creating a JFrame

There are two way to create a JFrame Window.

 By instantiating JFrame class.


 By extending JFrame class.

Limitations of AWT:

The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited
graphical interface. One reason for the limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents or peers. This means that the look and
feel of a component is defined by the platform, not by java. Because the AWT components use native code
resources, they are referred to as heavy weight.

The use of native peers led to several problems. First, because of variations between operating systems, a
component might look, or even act, differently on different platforms. This variability threatened java’s
philosophy: write once, run anywhere. Second, the look and feel of each component was fixed and could
not be changed. Third, the use of heavyweight components caused some frustrating restrictions.

MODEL-VIEW-CONTROLLER (MVC)

The Model-View-Controller (MVC) architecture in Java is a design pattern that provides a structured
approach for developing applications. It separates the application’s concerns into three main components:
the model, the view, and the controller. Each component has a specific role and responsibility within the
architecture.
Model:
The model represents the data and business logic of the application. It encapsulates the application’s data
and provides methods for accessing, manipulating, and updating that data. The model component is
independent of the user interface and focuses solely on the application’s functionality.

View:
The view is responsible for rendering the user interface and displaying the data to the user. It presents the
data from the model to the user in a visually appealing and understandable way. The view component does
not contain any business logic but instead relies on the model for data.

Controller:
The controller acts as an intermediary between the model and the view. It handles user input, processes
user actions, and updates the model or view accordingly. The controller interprets user actions and triggers
the appropriate methods in the model or view. It ensures the separation of concerns by keeping the view
and model independent of each other.

JAVA ABSTRACT WINDOW TOOLKIT(AWT)

Java AWT is an API that contains large number of classes and methods to create and manage graphical
user interface ( GUI ) applications.

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications 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 are using the resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below, all the classes are available in java.awt package.
Component class

Component class is at the top of AWT hierarchy. It is an abstract class that encapsulates all the attributes
of visual component. A component object is responsible for remembering the current foreground and
background colors and the currently selected text font.

Container

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.

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.

AWT Example

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

}}

Examples of GUI based Applications

 Automated Teller Machine (ATM)


 Airline Ticketing System
 Information Kiosks at railway stations
 Mobile Applications
 Navigation Systems
DIFFERENCES BETWEEN AWT AND SWINGS

LAYOUT MANAGERS

The Layout managers allow us to control the arrangement of visual components in GUI forms by
controlling the size and position of components inside containers. There is a layout manager associated
with each Container object. A layout manager is an instance of a class that implements the LayoutManager
interface.

Layout managers are available for general use in several AWT and Swing classes:

 BorderLayout
 BoxLayout
 CardLayout
 FlowLayout
 GridBagLayout
 GridLayout

Border Layout

This arrangement will show the components along the container's border. The component can be
presented in five different places on this layout: North, South, East, West, and Center are the locations.
The center is the default region.

There are 5 types of constructor in Border Layout. They are as following:

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

Example:

import java.awt.*;

public class BorderLayoutDemo

public static void main (String[]args)

Frame f1 = new Frame (); // creating frame

f1.setSize (250, 250);

// creating buttons

Button b1 = new Button ("UP");

Button b2 = new Button ("RIGHT");

Button b3 = new Button ("LEFT");

Button b4 = new Button ("DOWN");

Button b5 = new Button ("CENTER");

f1.add (b1, BorderLayout.NORTH); //placing b1 in north direction

f1.add (b2, BorderLayout.EAST); //placing b2 in east direction

f1.add (b3, BorderLayout.WEST); //placing b3 in west direction

f1.add (b4, BorderLayout.SOUTH); //placing b4 in south direction

f1.add (b5); // b5 will be placed in center by default

f1.setVisible (true);

}}
Box Layout

The BoxLayout places elements in a container either vertically in a single column or horizontally in a
single row. The components are assembled either top to bottom or left to right. The height of each
component will be the same and equal to the largest size component if the components are horizontally
aligned. The width of each component will be the same and equivalent to the greatest width component if
the components are vertically aligned.

X_Axis, Y_Axis, Line_Axis, and Page_Axis are the four constants that comprise the class. The horizontal
BoxLayout that the constant X_AXIS generates arranges each component from left to right. All
components are arranged vertically in a BoxLayout using the constant Y_AXIS, from top to bottom.

Example:

import java.awt.*;

import javax.swing.*;

public class BoxLayoutDemo extends Frame {

private static final long serialVersionUID = 1L;

Button buttons[];

public BoxLayoutDemo () {

buttons = new Button [5];

for (int i = 0;i<5;i++) {

buttons[i] = new Button ("Button " + (i + 1));

// adding the buttons

add (buttons[i]);

// placing the buttons horizontally


setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));

/* replace above line with

setLayout (new BoxLayout(this, BoxLayout.X_AXIS));

To arrange the buttons vertically */

setSize(500,500);

setVisible(true);

public static void main(String args[]){

BoxLayoutDemo b=new BoxLayoutDemo();

} }

Card Layout

The CardLayout arranges elements as a stack of cards. In a CardLayout, just the top card is visible.
CardLayout only shows one component at a time.

The top of the deck will be reserved for the first component to be inserted into the container. The card
components are presented horizontally or vertically, with a default gap of zero at the left, right, top, and
bottom edges.

There are 2 types of constructor in the Card Layout. They are as following:

1. CardLayout()

2. CardLayout(inthgap, intvgap)

Example:

import java.awt.*;

import java.awt.event.*;
import javax.swing.*;

public class CardDemo1 extends JFrame implements ActionListener

CardLayoutc_Card;

JButton box1,box2,box3;

Container d;

CardDemo1()

d=getContentPane();

c_Card=new CardLayout(40,30);

d.setLayout(c_Card);

box1=new JButton("studytonight_1");

box2=new JButton("studytonight_2");

box3=new JButton("studytonight_3");

box1.addActionListener(this);

box2.addActionListener(this);

box3.addActionListener(this);

d.add("P",box1);

d.add("Q",box2);

d.add("R",box3);

public void actionPerformed(ActionEvent e)

c_Card.next(d);

public static void main(String[] args)

CardDemo1 obj =new CardDemo1();

obj.setSize(500,500);
obj.setVisible(true);

obj.setDefaultCloseOperation(EXIT_ON_CLOSE);

} }

Flow Layout

Like words on a page, it puts the elements in a container. It completely occupies the top line from top to
bottom and left to right. If the container is not broad enough to display all the components, they are
wrapped around the line in the order that they are inserted, with the first component appearing at the top
left. Component spacing can be adjusted both vertically and horizontally. The components may be
positioned to the left, center, or right.

The FlowLayout class defines the following five constants to represent the five various alignments:

LEFT

RIGHT

CENTER

LEADING

TRAILING

There are 3 types of constructor in the Flow Layout. They are as following:

1. FlowLayout()

2. FlowLayout(int align)

3. FlowLayout(int align, inthgap, intvgap)

Example:

import java.awt.*;

import javax.swing.*;

public class FlowDemo1{

JFrame frame1;

FlowDemo1(){

frame1=new JFrame();

JButton box1=new JButton("1");

JButton box2=new JButton("2");

JButton box3=new JButton("3");

JButton box4=new JButton("4");

JButton box5=new JButton("5");


JButton box6=new JButton("6");

JButton box7=new JButton("7");

JButton box8=new JButton("8");

JButton box9=new JButton("9");

JButton box10=new JButton("10");

frame1.add(box1);

frame1.add(box2);

frame1.add(box3);

frame1.add(box4);

frame1.add(box5);

frame1.add(box6);

frame1.add(box7);

frame1.add(box8);

frame1.add(box9);

frame1.add(box10);

frame1.setLayout(new FlowLayout(FlowLayout.LEFT));

frame1.setSize(400,400);

frame1.setVisible(true);

public static void main(String[] args) {

new FlowDemo1();

} }

Gridbag Layout

It is a strong layout that organizes all the components into a grid of cells and keeps the object's
aspect ratio even when the container is modified. The size of the cells in this arrangement may vary. It
allocates components with a constant horizontal and vertical spacing. Using this feature, we can set a
default alignment for elements inside the columns or rows.
Constructors:

GridBagLayout(): A grid bag layout manager is made using the parameterless constructor.

Example:

import java.awt.*;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class GridbagDemo

public static void main (String[]args)

JFrame f1 = new JFrame ("GridBag Layout");

f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f1.setSize (250, 250);

GridBagLayout gb = new GridBagLayout ();

f1.setLayout (gb);

GridBagConstraints gc = new GridBagConstraints ();

//adding buttons

Button b1 = new Button ("Button1");

Button b2 = new Button ("Button2");

Button b3 = new Button ("Button3");

gc.fill = GridBagConstraints.HORIZONTAL;

gc.weightx = 0.5;

gc.weighty = 0.5;

gc.gridx = 0;

gc.gridy = 0;

f1.add (b1, gc);

gc.gridx = 1;

gc.gridy = 0;
f1.add (b2, gc);

gc.gridx = 2;

gc.gridy = 0;

f1.add (b3, gc);

Button b4 = new Button ("Button4");

gc.gridx = 0;

gc.gridy = 1;

gc.gridwidth = 3;

gc.ipady = 40;

Button b5 = new Button ("Button5");

gc.gridx = 2;

gc.gridy = 3;

gc.insets = new Insets (10, 0, 10, 0);

f1.add (b5, gc);

f1.pack ();

f1.setVisible (true);

}}

Grid Layout

It arranges each element in a grid of cells that are all the same size, adding each element from left to right
and top to bottom. Each grid area will be the same size, and each cell can only hold one component. All
cells are automatically adjusted when the container is changed in size. As the elements are added, the order
in which they should be placed in a cell is decided.

There are 3 types of constructor in Grid Layout. They are as following:

1. GridLayout()

2. GridLayout(int rows, int columns)


3. GridLayout(int rows, int columns, inthgap, int vgap)

Example:

import java.awt.Button;

import java.awt.GridLayout;

import javax.swing.JFrame;

public class GridLayoutDemo

JFrame frame;

Button buttons[];

// constructor

GridLayoutDemo()

frame = new JFrame(“Grid Layout”);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

buttons = new Button [9];

// adding the buttons.

for (int i = 0;i<9;i++) {

buttons[i] = new Button ("Button " + (i + 1));

frame.add (buttons[i]);

// since, we are using the non parameterized constructor, therefore;

// the number of columns is equal to the number of buttons we

// are adding to the frame. The row count remains one.

// setting the grid layout

// a 3 * 3 grid is created with the horizontal gap 10

// and vertical gap 10 ( all these customizations are optional)

//you can create grid layout simply using


// frame.setLayout(new GridLayout());

frame.setLayout(new GridLayout(3, 3, 10, 10));

frame.setSize(300, 300);

frame.setVisible(true);

public static void main(String argvs[])

new GridLayoutDemo();

Event Handling

Event:

An event is an object that describes a state change in a source. It can be generated as a consequence of a
person interacting with the elements in a GUI. Some of the activities that cause events to be generated are
pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse.

Foreground Events - Those events which require the direct interaction of user. They are generated as
consequences of a person interacting with the graphical components in Graphical User Interface. For
example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item
from list, scrolling the page etc.

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.
Event Handling: is the mechanism that controls the event and decides what should happen if an event
occurs. This mechanism have the code which is known as event handler that is executed when an event
occurs.

Event Handling Mechanisms:

1. Hierarchical Event Handling Model

2. Delegation Event Model

THE DELEGATION EVENT MODEL:

The modern approach to handling events is predicated on the delegation event model, which defines
standard and consistent mechanisms to get and process events. Its concept is sort of simple: a source
generates an occasion and sends it to at least one or more listeners. In this scheme, the listener simply
waits until it receives an occasion. Once an occasion is received, the listener processes the event and then
returns.

The advantage of this design is that the application logic that processes events is cleanly separated from
the user interface logic that generates those events.

A user interface element is able to ―delegate‖ the processing of an event to a separate piece of code. In the
delegation event model, listeners must register with a source in order to receive an event notification. This
provides an important benefit: notifications are sent only to listeners that want to receive them.

Components of Event Handling


Events

In the delegation model, an event is an object that describes a state change in a source.

Among other causes, an event can be generated as a consequence of a person interacting with the elements
in a graphical user interface.

Some of the activities that cause events to be generated are pressing a button, entering a character via the
keyboard, selecting an item in a list, and clicking the mouse.

Events may also occur that are not directly caused by interactions with a user interface.
Event Sources

A source is an object that generates an event. Generally sources are components. Sources may generate
more than one type of event.

A source must register listeners in order for the listeners to receive notifications about a specific type of
event. Each type of event has its own registration method. Here is the general form:

public void addTypeListener (TypeListener el )

Here, Type is the name of the event, and el is a reference to the event listener. For example, the method
that registers a keyboard event listener is called addKeyListener( ).

A source must also provide a method that allows a listener to unregister an interest in a specific type of
event. The general form of such a method is this: public void removeTypeListener(TypeListener el )

Event Listeners

A listener is an object that is notified when an event occurs. It has two major requirements. First, it
must have been registered with one or more sources to receive notifications about specific types of events.
Second, it must implement methods to receive and process these notifications.

The methods that receive and process events are defined in a set of interfaces, such as those found
in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved. Any object may receive and process one or both of
these events if it provides an implementation of this interface.

Sources of Events:

Event Source Description


Button Generates action events when the button is pressed
Check box Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked;
Menu item Generates action events when a menu item is selected; generates item events
when a checkable menu item is selected or deselected.
Scroll bar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Window Generates window events when a window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.
Event Classes and Listener Interfaces:

The classes that represent events are at the core of Java’s event handling mechanism. Widely used
Event classes are those defined by AWT and those defined by Swing.

The java.awt.event package provides many event classes and Listener interfaces for event
handling. At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the super
class for all events. It‘s one constructor is shown here:

EventObject(Object src) - Here, src is the object that generates this event.
The package java.awt.event defines many types of events that are generated by various user interface
elements

EVENT CLASS DESCRIPTION LISTENER


INTERFACE
ActionEvent Generated when a button is pressed, a list item is ActionListener
double-clicked, or a menu item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated. AdjustmentListener
ComponentEvent Generated when a component is hidden, moved, ComponentListener
resized, or becomes visible.
ContainerEvent Generated when a component is added to or removed ContainerListener
from a container.
FocusEvent Generated when a component gains or losses FocusListener
keyboard focus.
ItemEvent Generated when a check box or list item is clicked ItemListener
KeyEvent Generated when input is received from the keyboard. KeyListener
MouseEvent Generated when the mouse is dragged, moved, MouseListener and
clicked, pressed, or released; also generated when the MouseMotionListener
mouse enters or exits a component.
TextEvent Generated when the value of a text area or text field TextListener
is changed.
WindowEvent Generated when a window is activated, closed, WindowListener
deactivated, deiconified, iconified, opened, or quit.
The ActionEvent Class:

An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu


item is selected.

The ActionEvent class defines four integer constants that can be used to identify any modifiers
associated with an action event: ALT_MASK, CTRL_MASK, META_MASK (Ex. Escape), and
SHIFT_MASK.

ActionEvent has these three constructors:

 ActionEvent(Object src, int type, String cmd)


 ActionEvent(Object src, int type, String cmd, int modifiers)
 ActionEvent(Object src, int type, String cmd, long when, int modifiers)

The AdjustmentEvent Class:

An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.

BLOCK_DECREMENT The user clicked inside the scroll bar to decrease its value.
BLOCK_INCREMENT The user clicked inside the scroll bar to increase its value.
TRACK The slider was dragged.
UNIT_DECREMENT The button at the end of the scroll bar was clicked to decrease its value.
UNIT_INCREMENT The button at the end of the scroll bar was clicked to increase its value.
The ComponentEvent Class:

A ComponentEvent is generated when the size, position, or visibility of a component is changed.


There are four types of component events. The ComponentEvent class defines integer constants that can be
used to identify them:

COMPONENT_HIDDEN The component was hidden.


COMPONENT_MOVED The component was moved
COMPONENT_RESIZED The component was resized.
COMPONENT_SHOWN The component became visible.
ComponentEvent is the superclass either directly or indirectly of ContainerEvent, FocusEvent, KeyEvent,
MouseEvent, and WindowEvent, among others.

The ContainerEvent Class:

A ContainerEvent is generated when a component is added to or removed from a container. There are two
types of container events. The ContainerEvent class defines constants that can be used to identify them:
COMPONENT_ADDED and COMPONENT_REMOVED.

The FocusEvent Class:

A FocusEvent is generated when a component gains or loses input focus. These events are identified by the
integer constants FOCUS_GAINED and FOCUS_LOST.

The InputEvent Class:

The abstract class InputEvent is a subclass of ComponentEvent and is the super class for component input
events. Its subclasses are KeyEvent and MouseEvent.

The KeyEvent Class

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.

The MouseEvent Class:

There are eight types of mouse events. The MouseEvent class defines the following integer constants that
can be used to identify them:

MOUSE_CLICKED The user clicked the mouse


MOUSE_DRAGGED The user dragged the mouse
MOUSE_ENTERED The mouse entered a component
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved.
The TextEvent Class:

Instances of this class describe text events. These are generated by text fields and text areas when
characters are entered by a user or program. TextEvent defines the integer constant
TEXT_VALUE_CHANGED.

The WindowEvent Class:

The WindowEvent class defines integer constants that can be used to identify different types of events:

WINDOW_ACTIVATED The window was activated.


WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be
closed.
WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window was iconified.
WINDOW_ICONIFIED The window gained input focus.
WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.
EventListener Interfaces:

An event listener registers with an event source to receive notifications about the events of a particular
type. Various event listener interfaces defined in the java.awt.event package are given below:

INTERFACE DESCRIPTION
Defines the actionPerformed() method to receive and process action events.
ActionListener void actionPerformed(ActionEvent ae)

Defines five methods to receive mouse events, such as when a mouse is


clicked, pressed, released, enters, or exits a component void
MouseListener mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me) void mouseReleased(MouseEvent me)

Defines two methods to receive events, such as when a mouse is dragged or


MouseMotionListener moved.
void mouseDragged(MouseEvent me) void mouseMoved(MouseEvent me)

Defines the adjustmentValueChanged() method to receive and process the


AdjustmentListner adjustment events.
void adjustmentValueChanged(AdjustmentEvent ae)
Defines the textValueChanged() method to receive and process an event
TextListener when the text value changes.
void textValueChanged(TextEvent te)
Defines seven window methods to receive events.
void windowActivated(WindowEvent we) void
windowClosed(WindowEvent we) void windowClosing(WindowEvent we)
WindowListener void windowDeactivated(WindowEvent we) void
windowDeiconified(WindowEvent we) void
windowIconified(WindowEvent we) void windowOpened(WindowEvent
we)
ItemListener Defines the itemStateChanged() method when an item has been
void itemStateChanged(ItemEvent ie)
This interface defines two methods: windowGainedFocus( ) and
windowLostFocus( ). These are called when a window gains or loses input
WindowFocusListener focus. Their general forms are shown here:
void windowGainedFocus(WindowEvent we) void
windowLostFocus(WindowEvent we)
This interface defines four methods that are invoked when a component is
resized, moved, shown, or hidden. Their general forms are shown here:
ComponentListener void componentResized(ComponentEvent ce) void
componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce) void
componentHidden(ComponentEvent ce)

The ActionListener Interface


This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its
general form is shown here:

void actionPerformed(ActionEvent ae)

The AdjustmentListener Interface

This interface defines the adjustmentValueChanged( ) method that is invoked when an adjustment
event occurs. Its general form is shown here:

void adjustmentValueChanged(AdjustmentEvent ae)

The ComponentListener Interface

This interface defines four methods that are invoked when a component is resized, moved, shown,
or hidden. Their general forms are shown here:

void componentResized(ComponentEvent ce)

void componentMoved(ComponentEvent ce)

void componentShown(ComponentEvent ce)

void componentHidden(ComponentEvent ce)


The ContainerListener Interface

This interface contains two methods. When a component is added to a container,


componentAdded( ) is invoked. When a component is removed from a container, componentRemoved( ) is
invoked. Their general forms are shown here:

void componentAdded(ContainerEvent ce)

void componentRemoved(ContainerEvent ce)

The FocusListener Interface

This interface defines two methods. When a component obtains keyboard focus, focusGained( )

is invoked.

When a component loses keyboard focus, focusLost( ) is called.

Their general forms are shown here:

void focusGained(FocusEvent fe) void focusLost(FocusEvent fe)

The ItemListener Interface

This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes.
Its general form is shown here:

void itemStateChanged(ItemEvent ie)

The KeyListener Interface

This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked
when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has
been entered. For example, if a user presses and releases the A key, three events are generated in sequence:
key pressed, typed, and released. If a user presses and releases the HOME key, two key events are
generated in sequence: key pressed and released.

The general forms of these methods are shown here:

void keyPressed(KeyEvent ke)

void keyReleased(KeyEvent ke)

void keyTyped(KeyEvent ke)

The MouseListener Interface

This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is called.
When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked
when the mouse is pressed and released, respectively.
The general forms of these methods are shown here:

void mouseClicked(MouseEvent me)

void mouseEntered(MouseEvent me)

void mouseExited(MouseEvent me)

void mousePressed(MouseEvent me)

void mouseReleased(MouseEvent me)

The MouseMotionListener Interface

This interface defines two methods. The mouseDragged( ) method is called multiple times as the
mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved. Their
general forms are shown here:

void mouseDragged(MouseEvent me)

void mouseMoved(MouseEvent me)

The MouseWheelListener Interface

This interface defines the mouseWheelMoved( ) method that is invoked when the mouse wheel is moved.
Its general form is shown here:

void mouseWheelMoved(MouseWheelEvent mwe)

The TextListener Interface

This interface defines the textChanged( ) method that is invoked when a change occurs in a text area or
text field. Its general form is shown here:

void textChanged(TextEvent te)

The WindowFocusListener Interface

This interface defines two methods: windowGainedFocus( ) and windowLostFocus( ). These are
called when a window gains or loses input focus. Their general forms are shown here:

void windowGainedFocus(WindowEvent we)

void windowLostFocus(WindowEvent we)

The WindowListener Interface

This interface defines seven methods. The windowActivated( ) and windowDeactivated( ) methods
are invoked when a window is activated or deactivated, respectively. If a window is iconified, the
windowIconified( ) method is called. When a window is deiconified, the windowDeiconified( ) method is
called. When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called,
respectively. The windowClosing( ) method is called when a window is being closed. The general forms of
these methods are

void windowActivated(WindowEvent we)

void windowClosed(WindowEvent we)

void windowClosing(WindowEvent we)

void windowDeactivated(WindowEvent we)

void windowDeiconified(WindowEvent we)

void windowIconified(WindowEvent we)

void windowOpened(WindowEvent we)

Handling Mouse Events

To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces

Mouse event occurs when a mouse related activity is performed on a component such as clicking,
dragging, pressing, moving or releasing a mouse etc. Objects representing mouse events are created from
MouseEvent class.

The following applet demonstrates the process. It displays the current coordinates of the mouse in the
applet’s status window. Each time a button is pressed, the word “Down” is displayed at the location of the
mouse pointer. Each time the button is released, the word “Up” is shown. If a button is clicked, the
message “Mouse clicked” is displayed in the upperleft corner of the applet display area.

As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the
applet display area. When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is
dragged. The two variables, mouseX and mouseY, store the location of the mouse when a mouse pressed,
released, or dragged event occurs. These coordinates are then used by paint( ) to display output at the point
of these occurrences.

Methods of MouseListener interface:

public abstract void mouseClicked(MouseEvent e);

public abstract void mouseEntered(MouseEvent e);

public abstract void mouseExited(MouseEvent e);

public abstract void mousePressed(MouseEvent e);

public abstract void mouseReleased(MouseEvent e);

Methods of MouseMotionListener interface:

public abstract void mouseDragged(MouseEvent e);


public abstract void mouseMoved(MouseEvent e);

Handling Mouse Events Example Program:

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class MyMouse extends JFrame implements MouseListener

JLabel label;

MyMouse(){

addMouseListener(this);

label = new JLabel();

label.setBounds(90,80,130,20);

label.setFont(new Font("Serif", Font.BOLD, 20));

add(label);

setSize(250,250);

setLayout(null);

setVisible(true);

public void mouseClicked(MouseEvent e) {

label.setText("Clicked");

public void mouseEntered(MouseEvent e) {

label.setText("Entered");

public void mouseExited(MouseEvent e) {

label.setText("Exited");

public void mousePressed(MouseEvent e) {

label.setText("Pressed");
}

public void mouseReleased(MouseEvent e) {

label.setText("Released");

public static void main(String[] args) {

new MyMouse();

}}

Handling Key Board Events:

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.

It is a subclass of the abstract InputEvent class and is generated when the user presses or releases a key

is that you will be implementing the KeyListener interface.

Methods of KeyListener interface

public abstract void keyPressed(KeyEvent e);

public abstract void keyReleased(KeyEvent e);

public abstract void keyTyped(KeyEvent e);

When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed( )
event handler. When the key is released, a KEY_RELEASED event is generated and the keyReleased( )
handler is executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the
keyTyped( ) handler is invoked.

Example:

import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements KeyListener
{
String keystate="Hello PVPSIT"; String msg="";
MyFrame()
{
addKeyListener(this); addWindowListener(new MyWindow() );
}
public void keyPressed(KeyEvent ke)
{
keystate="Key Pressed"; msg+=ke.getKeyText( ke.getKeyCode()); repaint();
}
public void keyTyped(KeyEvent ke)
{
keystate="Key Typed"; repaint(); msg=msg+ke.getKeyChar();
}
public void keyReleased(KeyEvent ke)
{
keystate="Key Released"; repaint();
}
public void paint(Graphics g)
{
g.drawString(keystate,100,50); g.drawString(msg,100,100);
}
}
class KeyEventsExample
{
public static void main(String arg[])
{
MyFrame f=new MyFrame(); f.setTitle("Key Events Example"); f.setSize(500,300); f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}}

SUMMARY ABOUT EVENT HANDLING

Event handling has three main components:

Events : An event is a change in state of an object.

Events Source : Event source is an object that generates an event.

Listeners : A listener is an object that listens to the event. A listener gets notified when an event occurs.

Action: What user does is known as action. Example, a click over button. Here, click is the action
performed by the user.

ADAPTER CLASSES:

Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in
certain situations. An adapter class provides an empty implementation of all methods in an event listener
interface. Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface.

For example

MouseListener MouseAdapter

void mouseClicked(MouseEvent me) void mouseClicked(MouseEvent me){ }

void mouseEntered(MouseEvent me) void mouseEntered(MouseEvent me) { }


void mouseExited(MouseEvent me) void mouseExited(MouseEvent me) { }

void mousePressed(MouseEvent me) void mousePressed(MouseEvent me) { }

void mouseReleased(MouseEvent me) void mouseReleased(MouseEvent me) { }

Adapter Class Listener Interface


ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Example Program

import java.awt.*; import java.awt.event.*;

class WindowEx1 extends Frame

String msg;

WindowEx1(){

addWindowListener(new WA());

class WA extends WindowAdapter

public void windowClosing(WindowEvent we)

System.exit(0);

}}

class WindowAdapterEx

public static void main(String[] args) { WindowEx1 w=new WindowEx1(); w.setSize(400,400);


w.setLayout(null);

w.setVisible(true);

}}
Inner Classes:

Inner class is a class defined within another class, or even within an expression.

Listener classes are generally designed with just one purpose in mind: the creation of the listener object for
some GUI object (e.g., a button, window, checkbox, etc...). Given this relationship, separating the code for
the Listener class from the code for the class of the related GUI object seems to, in a certain sense, work
against the notion of the benefits of code encapsulation.

Fortunately, in Java, within the scope of one class, we are allowed to define one or more inner classes(or
nested classes). (Technically, the compiler turns an inner class into a regular class file named:
OuterClassName$InnerClassName.class.

Such inner classes can be defined inside the framing class, but outside its methods -- or it may even be
defined inside a method, and they can reference data and methods defined in the outer class in which it
nests

Example:

import java.awt.*; import java.awt.event.*;

class WindowEx1 extends Frame

String msg; WindowEx1(){

addWindowListener(new WA());

class WA extends WindowAdapter

public void windowClosing(WindowEvent we)

System.exit(0);

}}}

class WindowAdapterInner

public static void main(String[] args) { WindowEx1 w=new WindowEx1(); w.setSize(400,400);


w.setLayout(null);

w.setVisible(true);

}}
Anonymous Inner Classes:

An anonymous inner class is one that is not assigned a name.

Example:

import java.awt.*; import java.awt.event.*;

class WindowEx1 extends Frame

String msg; WindowEx1(){

addWindowListener(new WindowAdapter()

public void windowClosing(WindowEvent we)

System.exit(0);

}});}}

class WindowAdapterAnonymous

public static void main(String[] args) { WindowEx1 w=new WindowEx1(); w.setSize(400,400);


w.setLayout(null);

w.setVisible(true);

}}

A SIMPLE SWING APPLICATION, APPLETS

APPLETS:

An applet is a Java program that runs in a Web browser.(or) 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.

Applets are small Java applications that can be accessed on an Internet server, transported over Internet,
and can be automatically installed and run as apart of a web document.

After a user receives an applet, the applet can produce a graphical user interface. It has limited access to
resources so that it can run complex computations without introducing the risk of viruses or breaching data
integrity.

Any applet in Java is a class that extends the java.applet.Applet class.

An Applet class does not have any main() method. It is viewed using JVM. The JVM can use either a plug-
in of the Web browser or a separate runtime environment to run an applet application.
JVM creates an instance of the applet class and invokes init() method to initialize an Applet.

Advantage of Applet:

There are many advantages of applet. They are as follows:

•It works at client side so less response time.

•Secured

•It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os
etc.

Hierarchy of Applet :

As displayed in the diagram, Applet class extends Panel. Panel class extends Container, which is the
subclass of Component. Where Object class is base class for all the classes in java. JApplet class is
extension of Applet class.

Applet Life Cycle

The life cycle of an applet is as shown in the figure below:


The life cycle of an applet starts with init() method and ends with destroy() method. Other life cycle
methods are start(), stop() and paint(). The methods to execute only once in the applet life cycle are init()
and destroy(). Other methods execute multiple times.

init(): The init() method is the first method to execute when the applet is executed. Variable declaration
and initialization operations are performed in this method.

start(): The start() method contains the actual code of the applet that should run. The start() method
executes immediately after the init() method. It also executes whenever the applet is restored, maximized
or moving from one tab to another tab in the browser.

stop(): The stop() method stops the execution of the applet. The stop() method executes when the applet is
minimized or when moving from one tab to another in the browser.

destroy(): The destroy() method executes when the applet window is closed or when the tab containing the
webpage is closed. stop() method executes just before when destroy() method is invoked. The destroy()
method removes the applet object from memory.

paint(): The paint() method is used to redraw the output on the applet display area. The paint() method
executes after the execution of start() method and whenever the applet or browser is resized.

The method execution sequence when an applet is executed is:

 init()
 start()
 paint()

The method execution sequence when an applet is closed is:

 stop()
 destroy()

Applet HTML tag

The <applet> tag embeds a Java applet (mini Java applications) on the page. An applet is a program
written in the Java programming language that can be included in an HTML page, much in the same way
an image is included in a page.

Ex.

<applet code = demo.class width = 400 height = 200>

</applet>

Applet tag having three attribute


1. code – specifies name of the applet (.class file)
2. width – specifies width of the applet (in pixel )
3. height – specifies height of the applet ( in pixel )
Simple example of Applet:

To execute an Applet, FirstCreate an applet and compile it just like a simple java program.

First.java

importjava.applet.Applet;

importjava.awt.Graphics;

publicclassFirstextendsApplet

publicvoidpaint(Graphicsg)

g.drawString(“Welcome to Applet",50,150);

}}

Compile:

D:\> javac First.java

After successful compilation, we get First.classfile.

After that create an html file and place the applet code in html file

First.html

<html>

<body>

<applet code="First.class" width="300" height="300">

</applet>

</body>

</html>

Execute:

D:\> appletviewer First.html


How to run an Applet Program

An Applet program is compiled in the same way as you have been compiling your console programs.
However there are two ways to run an applet.

Executing the Applet within Java-compatible web browser.

Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer executes your applet in
a window

For executing an Applet in an web browser, create short HTML file in the same directory. Inside body tag
of the file, include the following code. (applet tag loads the Applet class)

Running Applet using Applet Viewer

To execute an Applet with an applet viewer, write short HTML file as discussed above. If name it
as run.htm, then the following command will run your applet program.

Security issues in Java applets include:

Code Execution: Applets could run arbitrary code on a user's computer, potentially leading to malware
infection or unauthorized access to system resources.

Outdated Java Versions: Users might have outdated Java installations with known vulnerabilities that
attackers could exploit.

Unsigned Applets: Even unsigned applets had limited access to system resources, raising the possibility
of malicious actions within the user's browser or system.

Certificate Problems: Signed applets were considered safer, but compromised or stolen certificates could
be used to distribute malicious applets.

Phishing: Malicious applets could be disguised as legitimate ones to trick users into running them.

Cross-Site Scripting (XSS): Applets could be exploited to facilitate cross-site scripting attacks,
compromising user data.
Browser Support: Major browsers phased out support for applets due to their security concerns.

Performance and Compatibility: Applets often suffered from slow loading times, performance issues,
and compatibility problems.

FEATURES OF JAVA APPLET:

The main features of the applet are discussed below.

Small size
Applets are typically small, making them easy to download and embed in web pages.
Browser-based
Applets run inside a web browser, providing a convenient way to add interactivity and dynamic content to
web pages.
Restricted access to resources
Applets are run in a sandboxed environment, which restricts their access to system resources such as
memory, processing power, and storage.
Limited user interaction
Applets typically provide limited user interaction, usually through HTML controls or UI components
provided by the applet itself.
Deployment
Applets are typically embedded in HTML pages using the <applet> tag or the newer <object> tag.
Platform-independent
Applets are written in Java and can run on any platform that supports a Java Virtual Machine (JVM),
which makes them highly portable.
Security
Applets provide a high level of security and cannot access system resources or sensitive information.

JAVA APPLICATION FEATURES

The main features of the application are discussed below.

Standalone
Applications are programs installed on a computer or other device and run independently of a web browser
or other software.
Access to Resources
Applications have access to system resources allowing them to perform complex tasks and manipulate
data.
User interaction
Applications provide user interaction through a GUI or CLI.
Deployment
They are generally distributed as executable files or installers. It can be downloaded and installed on a
computer or other device.
Platform-specific
They are usually developed for specific operating systems or hardware platforms.
Extensibility
Applications can be extended through plug-ins, add-ons, or other third-party software components.
DIFFERENCE BETWEEN APPLICATION AND APPLET

JAVA APPLICATION JAVA APPLET


An application is a standalone Java program that An applet is a form of Java program which is
can be run independently on a client/server without embedded with an HTML page and loaded by a
the need for a web browser. web server to be run on a web browser.
The execution of the program starts from the main() There is no requirement of main() method for the
method. execution of the program.
The application can access local disk files/ folders The applet doesn’t have access to the local network
and the network system. files and folders.
It doesn’t require any Graphical User Interface It must run within a GUI.
(GUI).
It is a trusted application and doesn’t require much It requires high-security constraints as applets are
security. untrusted.
It requires Java Runtime Environment (JRE) for its It requires a web browser like Chrome, Firefox, etc
successful execution. for its successful execution.
An application can perform read and write An applet doesn’t have access to local files so you
operations on files stored on the local disk. cannot perform read and write operations on files
stored on the local disk.
PARAMETERS PASSED TO AN APPLET

We can supply user defined parameter to an applet using tag . Param tag is used inside the applet
tag. Param tag has two attributes :

1. Name

2. Value

we will show you how to pass some parameters to an applet and how to read those parameters in an applet
to display their values in the output.

Steps to accomplish this task -:

To pass the parameters to the Applet we need to use the param attribute of <applet> tag

To retrieve a parameter's value, we need to use the getParameter() method of Applet class.

//program to demonstrate passing the parameters to applet

Java program saved as : UseParam.java

import java.applet.Applet;

java.awt.Graphics;

public class UseParam extends Applet

public void paint(Graphics g)

{
String str=getParameter("msg");

g.drawString(str,50, 50);

}}

Html document saved as : Myapplet.html

<html>

<body>

<applet code = “UseParam.class”width=”300”height=”300”>

<param name=”msg” values=”Welcome to applet”>

</applet>

</body>

</html>

Output:

Welcome to Applet

Repaint() Method:

The paint() method is called by the JVM implicitly in two circumstances. One is when the first time frame
is created and displayed. The other is when the frame is resized (by dragging the frame border with mouse)
by the user. If the programmer would like to call the paint() method in the middle of the coding, he is
permitted to call repaint() method. He is not permitted to call paint() method directly (Java repaint() Call
paint()). This method again call the paint method in the program. So the graphics get repaint again. The
second case, when paint() calls are generated is when the program calls repaint() or update().

The repaint() method is the one invoked by a program to do drawing. Their are 4 versions of this method
but the one with no arguments is usually used. Drawing via repaint() most often takes place in response to
user input.

repaint() ==> update() ==(usually calls)==> paint()

repaint() does not invoke paint() directly. It schedules a call to an intermediate method, update(). Finally,
update() calls paint() (unless you override update).
Update() Method

The update() method job is to erase the earlier drawings on the frame. On the cleared surface, the paint()
method draws a fresh with the latest graphics. If the programmer is allowed to call paint() method directly,
there is every possibility that he may forget to call the update() method explicitly. To avoid this and to
make Java as a robust language, the designers do not allow to call paint() directly.

//program to demonstrate repaint( ) and update( )

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.util.*;

public class PaintRepaintTest extends JPanel implements MouseListener

private Vector v;

public PaintRepaintTest()

v = new Vector();

setBackground(Color.white);

addMouseListener(this);

public void paint(Graphics g) // paint() method

super.paint(g);

g.setColor(Color.black);

Enumeration enumeration = v.elements();

while(enumeration.hasMoreElements()) {

Point p = (Point)(enumeration.nextElement());

g.drawRect(p.x-20, p.y-20, 40, 40);

}}
public void mousePressed(MouseEvent me) {

v.add(me.getPoint());

repaint(); // call repaint() method

public void mouseClicked(MouseEvent me) {}

public void mouseEntered(MouseEvent me) {}

public void mouseExited(MouseEvent me) {}

public void mouseReleased(MouseEvent me) {}

public static void main(String args[])

JFrame frame = new JFrame();

frame.getContentPane().add(new PaintRepaintTest());

frame.setTitle("PaintRepaint Test");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLocationRelativeTo(null);

frame.setSize(375, 250);

frame.setVisible(true);

}}

In the above program, if we click on the screen able to draw squares. In the mousePressed() method, we
can call the repaint() method.
Swing components

Swing provides a wide range of components that can be used to create GUIs. Swing Framework contains a
large set of components which provide rich functionalities and allow high level of customization. All these
components are lightweight components. They all are derived from JComponent class.Some of the most
commonly used components include:

 Buttons
 Text fields
 Labels
 Menus
 Panels
 Layout managers

JButton

JButton class provides functionality of a button. The button can include some display text or
images. It yields an event when clicked and double-clicked. JButton class has three constuctors,

JButton(Icon ic)

JButton(String str)

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.

Syntax:

JButton okBtn = new JButton(“Click”);

EXAMPLE:

import javax.swing.*;

public class Jbutton_Class{

public static void main(String[] args) {

JFrame f=new JFrame("JButton ");

JButton b=new JButton("Click Here");

b.setBounds(85,110,105,50);

f.add(b);

f.setSize(300,300);
f.setLayout(null);

f.setVisible(true);

} }

JLabel

JLabel is a Java Swing component. JLabel can show text, images, or a combination of the two. JLabel does not
respond to input events like mouse or keyboard focus.

Syntax:

JLabel textLabel = new JLabel(“This is 1st L...”);

The JLabel Contains four constructors. They are as follows:

JLabel(): It generates a blank label with no text or image.


JLabel(String s): It generates a new label with the provided string.
JLabel(Icon I): This produces a new label with an image.
JLabel(String s, Icon i, int align): Creates a new label containing a string, an image, and a given
horizontal alignment using this.
JLabel(Icon i, int align): Creates a JLabel instance with the picture and horizontal alignment that you
provide.
JLabel(String s, int align): Creates a JLabel instance with the text and horizontal alignment that you
provide.

Exаmple:

import javax.swing.*;

class Main

public static void main(String args[])

JFrame myframe= new JFrame("Simple JLabel Example");

JLabel label1,label2;
label1=new JLabel("This is 1st Label");

label1.setBounds(50,50, 100,30);

label2=new JLabel("This is 2nd Label");

label2.setBounds(50,100, 100,30);

myframe.add(label1); myframe.add(label2);

myframe.setSize(300,300);

myframe.setLayout(null);

myframe.setVisible(true); } }

JTextField

The JTextField renders an editable single-line text box. Users can input non-formatted text in the
box. We can initialize the text field by calling its constructor and passing an optional integer parameter.
This parameter sets the box width measured by the number of columns. Also, it does not limit the number
of characters that can be input into the box. It has three constructors:

JTextField(): It generates a new TextField Constructor.


JTextField(int columns): It generates a new empty TextField with the given number of columns.
JTextField(String text): Constructor for creating a new empty text field with the specified string as its
first value.
JTextField(String text, int columns): Constructor that generates a new empty textField with a specified
number of columns and the given string.
JTextField(Document doc, String text, int columns): Constructor for a textfield with the specified text
storage model and a number of columns.

Syntax:

JTextField txtBox = new JTextField(50);

Exаmple:

import javax.swing.*;

class Main
{

public static void main(String args[])

JFrame myframe= new JFrame("SimpleTextFieldExample");

JTextField text1,text2;

text1=new JTextField("Welcome to Codingninjas");

text1.setBounds(50,100, 200,30);

text2=new JTextField("JTextField in Java");

text2.setBounds(50,150, 200,30);

myframe.add(text1); myframe.add(text2);

myframe.setSize(400,400);

myframe.setLayout(null);

myframe.setVisible(true);

} }

JCheckBox:

The JCheckBox renders a check-box with a label. The check-box has two states, i.e., on and off. On
selecting, the state is set to "on," and a small tick is displayed inside the box.

Syntax:

CheckBox chkBox = new JCheckBox(“Java Swing”, true);


Constructors of JCheckBox

JCheckBox() - Initially, an unselected check box button is created with no text or icon.
JCheckBox(Action a) - This constructor creates a checkbox where the properties are taken from the
Action supplied.
JCheckBox(Icon icon) - This constructor initially creates an unselected checkbox with an icon.
JCheckBox(Icon icon, boolean selected) - It creates a checkbox with an icon that specifies if it is initially
selected or unselected.
JCheckBox(String text) - This constructor creates an unselected checkbox with the text.
JCheckBox(String text, boolean selected) - A checkbox with text is created and specifies if it is initially
selected or unselected.
JCheckBox(String text, Icon icon) - An unselected checkbox is created with the specified icon and text.
JCheckBox(String text, Icon icon, boolean selected) - A checkbox is created with text and icon and
specifies if it is initially selected or unselected.
Exаmple:

import java.awt.*;

import javax.swing.*;

class solve extends JFrame

static JFrame f;

public static void main(String[] args)

f = new JFrame("Coding Ninjas");

f.setLayout(new FlowLayout());

JCheckBox c1 = new JCheckBox("Ninja 1");

JCheckBox c2 = new JCheckBox("Ninja 2");

JPanel p = new JPanel();

p.add(c1);

p.add(c2);

f.add(p);

f.setSize(400, 400);

f.show();

}}
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.

Syntax:

JRadioButton jrb = new JRadioButton("Easy");

Exаmple:

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class Test extends JFrame

public Test()

JRadioButton jcb = new JRadioButton("A"); //creating JRadioButton.

add(jcb); //adding JRadioButton to frame.

jcb = new JRadioButton("B"); //creating JRadioButton.

add(jcb); //adding JRadioButton to frame.

jcb = new JRadioButton("C"); //creating JRadioButton.

add(jcb); //adding JRadioButton to frame.

jcb = new JRadioButton("none");

add(jcb);

setLayout(new FlowLayout());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(400, 400);

setVisible(true);

public static void main(String[] args)


{

new Test();

}}

JComboBox

Combo box is a combination of text fields and drop-down list.JComboBox component is used to
create a combo box in Swing.

Syntax:

JComboBox jcb = new JComboBox(name);

Exаmple:

import javax.swing.*;

public class ComboBoxExample {

JFrame f;

ComboBoxExample(){

f = new JFrame("ComboBox Example");

String country[]={“Apple”, “Guava”, “Grapes”, “Mango”, “Orange”};

JComboBox cb=new JComboBox(country);

cb.setBounds(50, 50,90,20);

f.add(cb);

f.setLayout(null);

f.setSize(400,500);

f.setVisible(true);

public static void main(String[] args) {

new ComboBoxExample();
}}

JTabbedPane

The JTabbedPane is another beneficial component that lets the user switch between tabs in an application.
It is a handy utility as it allows users to browse more content without navigating to different pages.

Syntax:

JTabbedPane jtabbedPane = new JTabbedPane();

jtabbedPane.addTab(“Tab_1”, new JPanel());

jtabbedPane.addTab(“Tab_2”, new JPanel());

The above code creates a two-tabbed panel with headings Tab_1 and Tab_2.

JMenuBar, JMenu and JMenuItem

In Java, the Swing toolkit contains a JMenuBar, JMenu, and JMenuItem class. It is under package
javax.swing.JMenuBar, javax.swing.JMenu and javax.swing.JMenuItem class. The JMenuBar class is used
for displaying menubar on the frame. The JMenu Object is used to pull down the menu bar's components.
The JMenuItem Object is used for adding the labeled menu item.

JMenuBar, JMenu and JMenuItem Declarations:

public class JMenuBar extends JComponent implements MenuElement, Accessible

public class JMenu extends JMenuItem implements MenuElement, Accessible

public class JMenuItem extends AbstractButton implements Accessible, MenuElement

JToggleButton

A JToggleButton is a button with two states. Selected and unselected are the two statuses. This
class is subclassed by the JRadioButton and JCheckBox classes. The toggle button toggles between being
pressed and unpressed when the user presses it. JToggleButton is a button that allows you to choose from a
list of options.

Constructors

JToggleButton(): Creates a toggle button with no text or image that is initially unselected.

JToggleButton(Action a): This method creates a toggle button with properties based on the Action.

JToggleButton(Icon icon): Creates a toggle button with the provided image but no text that is initially
unselected.

JToggleButton(Icon icon, boolean selected): Creates a toggle button with the provided image and
selection status, but no text.

JToggleButton(String text): Creates an unselected toggle button with the provided text.

JToggleButton(String text, boolean selected): Creates a toggle button with the supplied text and
selection status.

JToggleButton(String text, Icon icon): This method creates an unselected toggle button with the
provided text and image.

JToggleButton(String text, Icon icon, boolean selected): Creates a toggle button with the supplied text,
image, and selection status.

JAVA JSCROLLPANE

A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a scroll
pane to display a large component or a component whose size can change dynamically.

Constructors

JScrollPane()

JScrollPane(Component)

JScrollPane(int, int)

JScrollPane(Component, int, int)

JList

JList in Java is one of the Java Swing components. These components include buttons, sliders, list
boxes, checkboxes, etc. JList is defined in Java in the ‘java.swing’ package. JList is a component that
shows a list of objects and allows the user to choose one or more of them. JList is inherited from the
JComponent class. JComponent is an abstract class that serves as the foundation for all Swing
components.

Class Declaration

public class JList extends JComponent implements Scrollable, Accessible


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

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

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

JDialog

The JDialog control represents a top level window with a border and a title used to take some form
of input from the user. It inherits the Dialog class.

JDialog class declaration

public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer

Constructors:

JDialog() - It is used to create a modeless dialog without a title and without a specified Frame
owner.

JDialog(Frame owner) - It is used to create a modeless dialog with specified Frame as its owner
and an empty title.

JDialog(Frame owner, String title, boolean modal) - It is used to create a dialog with the specified
title, owner Frame and modality.

You might also like