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

Java AWT unit5

This document provides an overview of GUI programming with Swing, detailing the limitations of AWT, the MVC architecture, and various layout managers such as FlowLayout, BorderLayout, GridLayout, and CardLayout. It also covers event handling in Swing, the creation of simple Swing applications and applets, and the differences between AWT and Swing. Additionally, it includes examples of using different layout managers and components in Java GUI applications.

Uploaded by

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

Java AWT unit5

This document provides an overview of GUI programming with Swing, detailing the limitations of AWT, the MVC architecture, and various layout managers such as FlowLayout, BorderLayout, GridLayout, and CardLayout. It also covers event handling in Swing, the creation of simple Swing applications and applets, and the differences between AWT and Swing. Additionally, it includes examples of using different layout managers and components in Java GUI applications.

Uploaded by

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

Unit-5

GUI Programming with Swing – Introduction, limitations of AWT, MVC


architecture, components, containers. Understanding Layout Managers, Flow
Layout, Border Layout, Grid Layout, Card Layout, Grid Bag Layout.

Event Handling- The Delegation event model- Events, Event sources, Event
Listeners, Event classes, Handling mouse and keyboard events, Adapter classes,
Inner classes, Anonymous Inner classes.

A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets
and Applications, passing parameters to applets. Creating a Swing Applet, Painting
in Swing, A Paint example, Exploring Swing Controls- JLabel and Image Icon, JText
Field, The Swing ButtonsJButton, JToggle Button, JCheck Box, JRadio Button,
JTabbed Pane, JScroll Pane, JList, JCombo Box, Swing Menus, DialogsJava AWT

AWT stands for Abstract Window Toolkit. It is a platform dependent API for
creating Graphical User Interface (GUI) for java programs.

Why AWT is platform dependent? Java AWT calls native platform (Operating
systems) subroutine for creating components such as textbox, checkbox, button
etc. For example an AWT GUI having a button would have a different look and feel
across platforms like windows, Mac OS & Unix, this is because these platforms
have different look and feel for their native buttons and AWT directly calls their
native subroutine that creates the button. In simple, an application build on AWT
would look like a windows application when it runs on Windows, but the same
application would look like a Mac application when runs on Mac OS.

AWT is rarely used now a days because of its platform dependent and heavy-
weight nature. AWT components are considered heavy weight because they are
being generated by underlying operating system (OS). For example if you are
instantiating a text box in AWT that means you are actually asking OS to create a
text box for you.
Swing is a preferred API for window based applications because of its platform
independent and light-weight nature. Swing is built upon AWT API however it
provides a look and feel unrelated to the underlying platform. It has more
powerful and flexible components than AWT. In addition to familiar components
such as buttons, check boxes and labels, Swing provides several advanced
components such as tabbed panel, scroll panes, trees, tables, and lists.

AWT:
Characteristics
 It is a set of native user interface components.
 It is very robust in nature.
 It includes various editing tools like graphics tool and imaging tools.
 It uses native window-system controls.
 It provides functionality to include shapes, colors and font classes.
Advantages
 It takes very less memory for development of GUI and executing programs.
 It is highly stable as it rarely crashes.
 It is dependent on operating system so performance is high.
 It is easy to use for beginners due to its easy interface.
Disadvantages
 The buttons of AWT does not support pictures.
 It is heavyweight in nature.
 Two very important components trees and tables are not present.
 Extensibility is not possible as it is platform dependent
AWT hierarchy
The hierarchy of Java AWT classes are given below.
Components and containers
All the elements like buttons, text fields, scrollbars etc are known as components.
In AWT we have classes for each component as shown in the above diagram. To
have everything placed on a screen to a particular position, we have to add them
to a container. A container is like a screen wherein we are placing components
like buttons, text fields, checkbox etc. In short a container contains and controls
the layout of components. A container itself is a component (shown in the above
hierarchy diagram) thus we can add a container inside container.

Types of containers:
As explained above, a container is a place where in we add components like text
field, button, checkbox etc. There are four types of containers available in AWT:
Window, Frame, Dialog and Panel. As shown in the hierarchy diagram above,
Frame and Dialog are subclasses of Window class.

Window: Window is a container that has no border and menubars. You must use
frame, dialog or another window for creating a window.

Dialog: Dialog class has border and title. An instance of the Dialog class cannot
exist without an associated instance of the Frame class.
Panel: Panel does not contain title bar, menu bar or border. An instance of the
Panel class provides a container to which to add components.

Frame: A frame has title, border and menu bars. It can contain several
components like buttons, text fields, scrollbars etc. This is most widely used
container while developing an application in AWT.
Useful Methods of Component class
Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int sets the size (width and height) of the
height) component.

public void setLayout(LayoutManager defines the layout manager for the


m) component.

public void setVisible(boolean status) changes the visibility of the component, by


default false.

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a
frame in AWT.
By extending Frame class (inheritance)
By creating the object of Frame class (association)
AWT Example by Inheritance
import java.awt.*;
public 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();
}}
Output:

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the
above example that sets the position of the awt button.

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class.
Here, we are showing Button component on the Frame.
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}

What is MVC Architecture in Java?


Model designs based on MVC architecture follow the MVC design pattern and
they separate the application logic from the user interface when designing
software. As the name implies MVC pattern has three layers, which are:
 Model – Represents the business layer of the application
 View – Defines the presentation of the application
 Controller – Manages the flow of the application
In Java Programming context, the Model consists of simple Java classes, the View
displays the data and the Controller consists of servlets. This separation results in
user requests being processed as follows:
1. The browser on the client sends a request for a page to the controller
present on the server
2. The controller performs the action of invoking the model, thereby,
retrieving the data it needs in response to the request
3. The controller then gives the retrieved data to the view
4. The view is rendered and sent back to the client for the browser to display

Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers. These are the following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south,
east, west and center. Each region (area) may contain one component only. It is
the default layout of frame or window. 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 JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

Example of BorderLayout class:

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");
10. JButton b2=new JButton("SOUTH");
11. JButton b3=new JButton("EAST");
12. JButton b4=new JButton("WEST");
13. JButton b5=new JButton("CENTER");
14. f.setLayout(new BorderLayout(20,30));
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22.
23. f.setVisible(true);
24.f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
25.}
26.public static void main(String[] args) {
27. new Border();
28.}
29.}
Output:
Java GridLayout
The GridLayout is used to arrange the components in 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 alongwith given horizontal and vertical
gaps.

Example of GridLayout class

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8. JButton b1=new JButton("1");
9. JButton b2=new JButton("2");
10. JButton b3=new JButton("3");
11. JButton b4=new JButton("4");
12. JButton b5=new JButton("5");
13. JButton b6=new JButton("6");
14. JButton b7=new JButton("7");
15. JButton b8=new JButton("8");
16. JButton b9=new JButton("9");
17.
18. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
19. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
20.
21. f.setLayout(new GridLayout(3,3)); //setting grid layout of 3 rows and 3 columns
22. f.setSize(300,300);
23. f.setVisible(true);
24.f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
25.}
26.public static void main(String[] args) {
27. new MyGridLayout();
28.}
29.}

Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in
a flow). It is the default layout of applet or panel.
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.
Example of FlowLayout class

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
16.
17. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
18. //setting flow layout of right alignment
19.
20. f.setSize(300,300);
21. f.setVisible(true);
22.f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
23.}
24.public static void main(String[] args) {
25. new MyFlowLayout();
26.}
27.}
Java CardLayout
The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is
known as CardLayout.
Constructors of CardLayout class
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
Commonly used methods of CardLayout class
o public void next(Container parent): is used to flip to the next card of the
given container.
o public void previous(Container parent): is used to flip to the previous card
of the given container.
o public void first(Container parent): is used to flip to the first card of the
given container.
o public void last(Container parent): is used to flip to the last card of the
given container.
o public void show(Container parent, String name): is used to flip to the
specified card with the given name.
Example of CardLayout class

1. import java.awt.*;
2. import java.awt.event.*;
3.
4. import javax.swing.*;
5.
6. public class CardLayoutExample extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExample(){
11.
12. c=getContentPane();
13. card=new CardLayout(40,30);
14.//create CardLayout object with 40 hor space and 30 ver space
15. c.setLayout(card);
16.
17. b1=new JButton("Apple");
18. b2=new JButton("Boy");
19. b3=new JButton("Cat");
20. b1.addActionListener(this);
21. b2.addActionListener(this);
22. b3.addActionListener(this);
23.
24. c.add("a",b1);c.add("b",b2);c.add("c",b3);
25.
26. }
27. public void actionPerformed(ActionEvent e) {
28. card.next(c);
29. }
30.
31. public static void main(String[] args) {
32. CardLayoutExample cl=new CardLayoutExample();
33. cl.setSize(400,400);
34. cl.setVisible(true);
35. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
36. }
37.}

Ex: Display the images on button

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class CardLayoutExample extends JFrame implements ActionListener{

CardLayout card;

JButton b1,b2,b3;

Container c;
CardLayoutExample(){

c=getContentPane();

card=new CardLayout(40,30);

//create CardLayout object with 40 hor space and 30 ver space

c.setLayout(card);

Icon icon = new ImageIcon("E:\\501\\apple.jpg");

Icon icon1 = new ImageIcon("E:\\501\\ball.jpg");

Icon icon2 = new ImageIcon("E:\\501\\cat.jpg");

b1=new JButton(icon);

b2=new JButton(icon1);

b3=new JButton(icon2);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

c.add("a",b1);c.add("b",b2);c.add("c",b3);

public void actionPerformed(ActionEvent e) {

card.next(c);

}
public static void main(String[] args) {

CardLayoutExample cl=new CardLayoutExample();

cl.setSize(400,400);

cl.setVisible(true);

cl.setDefaultCloseOperation(EXIT_ON_CLOSE);

}
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as
its display area. Each component associates an instance of GridBagConstraints. With the
help of constraints object we arrange component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine component's size.
Fields
Modifier and Type Field Description

double[] columnWeights It is used


to hold
the
overrides
to the
column
weights.

int[] columnWidths It is used


to hold
the
overrides
to the
column
minimum
width.

protected comptable It is used


Hashtable<Component,GridBagConst to
raints> maintains
the
associatio
n between
a
componen
t and its
gridbag
constraint
s.

protected GridBagConstraints defaultConstrai It is used


nts to hold a
gridbag
constraint
s instance
containing
the
default
values.

protected GridBagLayoutInfo layoutInfo It is used


to hold
the layout
informatio
n for the
gridbag.

protected static int MAXGRIDSIZE No longer


in use just
for
backward
compatibil
ity

protected static int MINSIZE It is


smallest
grid that
can be laid
out by the
grid bag
layout.

protected static int PREFERREDSIZE It is


preferred
grid size
that can
be laid out
by the grid
bag
layout.

int[] rowHeights It is used


to hold
the
overrides
to the row
minimum
heights.

double[] rowWeights It is used


to hold
the
overrides
to the row
weights.

Useful Methods
Modifier and Type Method Description

void addLayoutComponent(Component It adds specified


comp, Object constraints) component to
the layout, using
the specified
constraints
object.

void addLayoutComponent(String name, It has no effect,


Component comp) since this layout
manager does
not use a per-
component
string.

protected void adjustForGravity(GridBagConstraints It adjusts the x, y,


constraints, Rectangle r) width, and height
fields to the
correct values
depending on the
constraint
geometry and
pads.

protected void AdjustForGravity(GridBagConstraints This method is


constraints, Rectangle r) for backwards
compatibility
only

protected void arrangeGrid(Container parent) Lays out the grid.

protected void ArrangeGrid(Container parent) This method is


obsolete and
supplied for
backwards
compatibility

GridBagConstraints getConstraints(Component comp) It is for getting


the constraints
for the specified
component.
float getLayoutAlignmentX(Container It returns the
parent) alignment along
the x axis.

float getLayoutAlignmentY(Container It returns the


parent) alignment along
the y axis.

int[][] getLayoutDimensions() It determines


column widths
and row heights
for the layout
grid.

protected getLayoutInfo(Container parent, int This method is


GridBagLayoutInfo sizeflag) obsolete and
supplied for
backwards
compatibility.

protected GetLayoutInfo(Container parent, int This method is


GridBagLayoutInfo sizeflag) obsolete and
supplied for
backwards
compatibility.

Point getLayoutOrigin() It determines the


origin of the
layout area, in
the graphics
coordinate space
of the target
container.

double[][] getLayoutWeights() It determines the


weights of the
layout grid's
columns and
rows.

protected getMinSize(Container parent, It figures out the


Dimension GridBagLayoutInfo info) minimum size of
the master based
on the
information from
getLayoutInfo.

protected GetMinSize(Container parent, This method is


Dimension GridBagLayoutInfo info) obsolete and
supplied for
backwards
compatibility
only

Example

import java.awt.Button;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import javax.swing.*;

public class GridBagLayoutExample extends JFrame{

public static void main(String[] args) {

GridBagLayoutExample a = new GridBagLayoutExample();

public GridBagLayoutExample() {
GridBagLayout grid = new GridBagLayout();

GridBagConstraints gbc = new GridBagConstraints();

setLayout(grid);

setTitle("GridBag Layout Example");

GridBagLayout layout = new GridBagLayout();

this.setLayout(layout);

gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.gridx = 0;

gbc.gridy = 0;

this.add(new Button("Button One"), gbc);

gbc.gridx = 1;

gbc.gridy = 0;

this.add(new Button("Button two"), gbc);

gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.ipady = 20;

gbc.gridx = 0;

gbc.gridy = 1;

this.add(new Button("Button Three"), gbc);

gbc.gridx = 1;

gbc.gridy = 1;

this.add(new Button("Button Four"), gbc);

gbc.gridx = 0;
gbc.gridy = 2;

gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.gridwidth = 2;

this.add(new Button("Button Five"), gbc);

setSize(300, 300);

setPreferredSize(getSize());

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}
Event Handling

Changing the state of an object is known as an event. For example, click on


button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.

Delegation Event Model in Java


The Delegation Event model is defined to handle events in GUI programming
languages. The GUI stands for Graphical User Interface, where a user
graphically/visually interacts with the system.
The GUI programming is inherently event-driven; whenever a user initiates an
activity such as a mouse activity, clicks, scrolling, etc., each is known as an event
that is mapped to a code to respond to functionality to the user. This is known as
event handling.
But, the modern approach for event processing is based on the Delegation Model.
It defines a standard and compatible mechanism to generate and process events.
In this model, a source generates an event and forwards it to one or more
listeners. The listener waits until it receives an event. Once it receives the event, it
is processed by the listener and returns it. The UI elements are able to delegate
the processing of an event to a separate function.
The key advantage of the Delegation Event Model is that the application logic is
completely separated from the interface logic.
In this model, the listener must be connected with a source to receive the event
notifications. Thus, the events will only be received by the listeners who wish to
receive them. So, this approach is more convenient than the inheritance-based
event model
Basically, an Event Model is based on the following three components:
o Events
o Events Sources
o Events Listeners
Events
The Events are the objects that define state change in a source. An event can be
generated as a reaction of a user while interacting with GUI elements. Some of
the event generation activities are moving the mouse pointer, clicking on a
button, pressing the keyboard key, selecting an item from the list, and so on. We
can also consider many other user operations as events.
The Events may also occur that may be not related to user interaction, such as a
timer expires, counter exceeded, system failures, or a task is completed, etc. We
can define events for any of the applied actions.
Event Sources
A source is an object that causes and generates an event. It generates an event
when the internal state of the object is changed. The sources are allowed to
generate several different types of events.
A source must register a listener to receive notifications for a specific event. Each
event contains its registration method. Below is an example:
1. public void addTypeListener (TypeListener e1)
From the above syntax, the Type is the name of the event, and e1 is a reference
to the event listener. For example, for a keyboard event listener, the method will
be called as addKeyListener(). For the mouse event listener, the method will be
called as addMouseMotionListener().
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners
require two things; first, it must be registered with a source; however, it can be
registered with several resources to receive notification about the events. Second,
it must implement the methods to receive and process the received notifications.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener
KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Java event handling by implementing ActionListener for Button class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class AEvent extends JFrame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
Output:

Java event handling by implementing ActionListener for Label class


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class LabelExample extends JFrame implements ActionListener{


TextField tf; Label l; Button b;

LabelExample(){

tf=new TextField();

tf.setBounds(50,50, 150,20);

l=new Label();

l.setBounds(50,100, 250,20);

b=new Button("Find IP");

b.setBounds(50,150,60,30);

b.addActionListener(this); //register

add(b);add(tf);add(l);

setSize(400,400);

setLayout(null);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

public void actionPerformed(ActionEvent e) {

try{

String host=tf.getText();

String ip=java.net.InetAddress.getByName(host).getHostAddress();

l.setText("IP of "+host+" is: "+ip);

}catch(Exception ex){System.out.println(ex);}

}
public static void main(String[] args) {

new LabelExample();

Output:

Java AWT TextField Example with ActionListener


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class TextFieldExample extends JFrame implements ActionListener{

TextField tf1,tf2,tf3;

Button b1,b2;

TextFieldExample(){

tf1=new TextField();

tf1.setBounds(50,50,150,20);

tf2=new TextField();

tf2.setBounds(50,100,150,20);

tf3=new TextField();

tf3.setBounds(50,150,150,20);

tf3.setEditable(false);

b1=new Button("+");

b1.setBounds(50,200,50,50);

b2=new Button("-");

b2.setBounds(120,200,50,50);

b1.addActionListener(this);

b2.addActionListener(this);

add(tf1);add(tf2);add(tf3);add(b1);add(b2);

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

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

public void actionPerformed(ActionEvent e) {

String s1=tf1.getText();

String s2=tf2.getText();

int a=Integer.parseInt(s1);

int b=Integer.parseInt(s2);

int c=0;

if(e.getSource()==b1)

// The getSource method is used in the actionPerformed method to determine which button
was //clicked.

c=a+b;

}else if(e.getSource()==b2){

c=a-b;

String result=String.valueOf(c);

tf3.setText(result);

public static void main(String[] args) {


new TextFieldExample();

Output:
Java AWT Checkbox Example with ActionListener

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class CheckboxExample

CheckboxExample(){

JFrame f= new JFrame("CheckBox Example");

final Label label = new Label();

label.setAlignment(Label.CENTER);

label.setSize(400,100);

Checkbox checkbox1 = new Checkbox("C++");

checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java");

checkbox2.setBounds(100,150, 50,50);

f.add(checkbox1); f.add(checkbox2); f.add(label);

checkbox1.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent e) {

label.setText("C++ Checkbox: "

+ (e.getStateChange()==1?"checked":"unchecked"));

});

checkbox2.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent e) {

label.setText("Java Checkbox: "

+ (e.getStateChange()==1?"checked":"unchecked"));

});

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String args[])

{
new CheckboxExample();

Output:
Java AWT Choice Example with ActionListener
import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class ChoiceExample

ChoiceExample(){

JFrame f= new JFrame();

final Label label = new Label();

label.setAlignment(Label.CENTER);

label.setSize(400,100);

Button b=new Button("Show");

b.setBounds(200,100,50,20);

final Choice c=new Choice();

c.setBounds(100,100, 75,75);

c.add("C");

c.add("C++");

c.add("Java");

c.add("PHP");

c.add("Python");

f.add(c);f.add(label); f.add(b);

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

f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

b.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String data = "Programming language Selected: "+


c.getItem(c.getSelectedIndex());

label.setText(data);

});

public static void main(String args[])

new ChoiceExample();

Output:
Java AWT List Example with ActionListener
import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class ListExample

{
ListExample(){

JFrame f= new JFrame();

final Label label = new Label();

label.setAlignment(Label.CENTER);

label.setSize(500,100);

Button b=new Button("Show");

b.setBounds(200,150,80,30);

final List l1=new List(4, false);

l1.setBounds(100,100, 70,70);

l1.add("C");

l1.add("C++");

l1.add("Java");

l1.add("PHP");

final List l2=new List(4, true);

l2.setBounds(100,200, 70,70);

l2.add("Turbo C++");

l2.add("Spring");

l2.add("Hibernate");

l2.add("CodeIgniter");

f.add(l1); f.add(l2); f.add(label); f.add(b);

f.setSize(450,450);

f.setLayout(null);
f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

b.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String data = "Programming language Selected:


"+l1.getItem(l1.getSelectedIndex());

data += ", Framework Selected:";

for(String frame:l2.getSelectedItems()){

data += frame + " ";

label.setText(data);

});

public static void main(String args[])

new ListExample();

Output
Java AWT TextArea Example with ActionListener
import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class TextAreaExample extends JFrame implements ActionListener{

Label l1,l2;

TextArea area;

Button b;

TextAreaExample(){

l1=new Label();

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

l2=new Label();

l2.setBounds(160,50,100,30);

area=new TextArea();
area.setBounds(20,100,300,300);

b=new Button("Count Words");

b.setBounds(100,400,100,30);

b.addActionListener(this);

add(l1);add(l2);add(area);add(b);

setSize(400,500);

setLayout(null);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

public void actionPerformed(ActionEvent e){

String text=area.getText();

String words[]=text.split("\\s");

l1.setText("Words: "+words.length);

l2.setText("Characters: "+text.length());

public static void main(String[] args) {

new TextAreaExample();

}
Output:

Java AWT MenuItem and Menu Example


import java.awt.*;

import javax.swing.*;

class MenuExample

MenuExample(){

JFrame f= new JFrame("Menu and MenuItem Example");

MenuBar mb=new MenuBar();


Menu menu=new Menu("Menu");

Menu submenu=new Menu("Sub Menu");

MenuItem i1=new MenuItem("Item 1");

MenuItem i2=new MenuItem("Item 2");

MenuItem i3=new MenuItem("Item 3");

MenuItem i4=new MenuItem("Item 4");

MenuItem i5=new MenuItem("Item 5");

menu.add(i1);

menu.add(i2);

menu.add(i3);

submenu.add(i4);

submenu.add(i5);

menu.add(submenu);

mb.add(menu);

f.setMenuBar(mb);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String args[])

{
new MenuExample();

Output:

Handling mouse and keyboard events:

Java MouseListener Interface


The Java MouseListener is notified whenever you change the state
of mouse. It is notified against MouseEvent. The MouseListener
interface is found in java.awt.event package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are
given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
Java MouseListener Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseListenerExample2 extends JFrame
implements MouseListener{
MouseListenerExample2(){
addMouseListener(this);

setSize(300,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

public static void main(String[] args) {


new MouseListenerExample2();
}
}
Output:
Java MouseMotionListener Interface
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
The signature of 2 methods found in MouseMotionListener interface are given below:
1. public abstract void mouseDragged(MouseEvent e);
2. public abstract void mouseMoved(MouseEvent e);
Java MouseMotionListener Example
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class Paint extends JFrame implements MouseMotionListener{
Label l;
Color c=Color.BLUE;
Paint(){
l=new Label();
l.setBounds(20,40,100,20);
add(l);

addMouseMotionListener(this);

setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseDragged(MouseEvent e) {
l.setText("X="+e.getX()+", Y="+e.getY());
Graphics g=getGraphics();
g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {
l.setText("X="+e.getX()+", Y="+e.getY());
}
public static void main(String[] args) {
new Paint();
}
}
output:

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. It has
three methods.
Methods of KeyListener interface
The signature of 3 methods found in KeyListener interface are given below:
1. public abstract void keyPressed(KeyEvent e);
2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);

Java KeyListener Example : Count Words & Characters

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class KeyListenerExample extends JFrame implements KeyListener{

Label l;

TextArea area;

KeyListenerExample(){
l=new Label();

l.setBounds(20,50,200,20);

area=new TextArea();

area.setBounds(20,80,300, 300);

area.addKeyListener(this);

add(l);add(area);

setSize(400,400);

setLayout(null);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

public void keyPressed(KeyEvent e) {}

public void keyReleased(KeyEvent e) {

String text=area.getText();

String words[]=text.split("\\s");

l.setText("Words: "+words.length+" Characters:"+text.length());

public void keyTyped(KeyEvent e) {}

public static void main(String[] args) {


new KeyListenerExample();

Adapter classes

Java Adapter Classes


Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
java.awt.event Adapter classes
Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

Java WindowAdapter Example


import java.awt.*;

import java.awt.event.*;

public class AdapterExample{


Frame f;

AdapterExample(){

f=new Frame("Window Adapter");

f.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e) {

f.dispose(); // this method is used to close the window

});

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main(String[] args) {

new AdapterExample();

Output:
Inner classes

Java Inner Classes


Java inner class or nested class is a class which is declared inside the class or
interface.
We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.
Additionally, it can access all the members of outer class including private data
members and methods.

Syntax of Inner class


1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }

Advantage of java inner classes


There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable
code because it logically group classes and interfaces in one place only. SQL CREATE
TABLE
3) Code Optimization: It requires less code to write.
Anonymous Inner classes.

Java Anonymous inner class


A class that have no name is known as anonymous inner class in java. It should be used
if you have to override method of class or interface. Java Anonymous inner class can be
created by two ways:
1. Class (may be abstract or concrete).
2. Interface

Java anonymous inner class example using class


abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
Output:
nice fruits
Java anonymous inner class example using interface
interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
Output:
nice fruits

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.

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.
Java Swing Examples
There are two ways to create a frame:
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other
method.
Let's see a simple swing example where we are creating one button and adding it
on the JFrame object inside the main() method.
Example of Swing by Association inside constructor
We can also write all the codes of creating JFrame, JButton and method call inside
the java constructor.
File: Simple.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Ex: Simple example of Swing by inheritance

import javax.swing.*;
public class Simple2 extends JFrame{ //inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);

add(b);//adding button on frame


setSize(400,500);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Simple2();
}}

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.
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 AbstractButton 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 the


button.

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 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 JButton Example with ActionListener


import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome to Javatpoint.");
}
} );
f.add(b);f.add(tf);
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.

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 contents


alignment) along the X axis.

Icon getIcon() It returns the graphic image that the label


displays.

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


contents along the X axis.

Java JLabel Example


1. import javax.swing.*;
2. class LabelExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1); f.add(l2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }

1.
2.
3.
4.
JTextField class declaration
Let's see the declaration for javax.swing.JTextField class.
1. public class JTextField extends JTextComponent implements SwingConstants
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
columns) text and columns.

JTextField(int columns) Creates a new empty TextField with the specified


number of columns.

Commonly used Methods:


Methods Description

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


l) 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 It is used to remove the specified action


removeActionListener(ActionListener l) listener so that it no longer receives action
events from this textfield.

5.
6. import javax.swing.*;
7. class TextFieldExample
8. {
9. public static void main(String args[])
10. {
11. JFrame f= new JFrame("TextField Example");
12. JTextField t1,t2;
13. t1=new JTextField("Welcome to Java
14..");
15. t1.setBounds(50,100, 200,30);
16. t2=new JTextField("AWT Tutorial");
17. t2.setBounds(50,150, 200,30);
18. f.add(t1); f.add(t2);
19. f.setSize(400,400);
20. f.setLayout(null);
21. f.setVisible(true);
22. }
23. }

Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on
or off.
Nested Classes
Modifier Class Description
and Type

protected JToggleButton.AccessibleJToggleButton This class implements


class accessibility support for the
JToggleButton class.

static class JToggleButton.ToggleButtonModel The ToggleButton model

Constructors
Constructor Description
JToggleButton() It creates an initially unselected toggle button
without setting the text or image.

JToggleButton(Action a) It creates a toggle button where properties are


taken from the Action supplied.

JToggleButton(Icon icon) It creates an initially unselected toggle button


with the specified image but no text.

JToggleButton(Icon icon, boolean It creates a toggle button with the specified


selected) image and selection state, but no text.

JToggleButton(String text) It creates an unselected toggle button with the


specified text.

JToggleButton(String text, boolean It creates a toggle button with the specified


selected) text and selection state.

JToggleButton(String text, Icon It creates a toggle button that has the specified
icon) text and image, and that is initially unselected.

JToggleButton(String text, Icon It creates a toggle button with the specified


icon, boolean selected) text, image, and selection state.

Methods
Modifier and Type Method Description

AccessibleContex getAccessibleContext() It gets the AccessibleContext


t associated with this JToggleButton.

String getUIClassID() It returns a string that specifies the


name of the l&f class that renders this
component.
protected String paramString() It returns a string representation of
this JToggleButton.

void updateUI() It resets the UI property to a value


from the current look and feel.

JToggleButton Example
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;

public class JToggleButtonExample extends JFrame implements ItemListener {


public static void main(String[] args) {
new JToggleButtonExample();
}
private JToggleButton button;
JToggleButtonExample() {
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton() {
button = new JToggleButton("ON");
add(button);
}
private void setAction() {
button.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve) {
if (button.isSelected())
button.setText("OFF");
else
button.setText("ON");
}
}
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.
1. public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:


Constructor Description

JJCheckBox() Creates an initially unselected check box button with no


text, no icon.

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


JCheckBox(String text, boolean Creates a check box with text and specifies whether or
selected) not it is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.

Commonly used Methods:


Methods Description

AccessibleContext It is used to get the AccessibleContext associated with


getAccessibleContext() this JCheckBox.

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

Java JCheckBox Example with ItemListener


import javax.swing.*;

import java.awt.event.*;

public class CheckBoxExample

CheckBoxExample(){

JFrame f= new JFrame("CheckBox Example");

final JLabel label = new JLabel();

label.setHorizontalAlignment(JLabel.CENTER);

label.setSize(400,100);

JCheckBox checkbox1 = new JCheckBox("C++");

checkbox1.setBounds(150,100, 50,50);

JCheckBox checkbox2 = new JCheckBox("Java");

checkbox2.setBounds(150,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);

checkbox1.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent e) {

label.setText("C++ Checkbox: "

+ (e.getStateChange()==1?"checked":"unchecked"));

});

checkbox2.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent e) {

label.setText("Java Checkbox: "

+ (e.getStateChange()==1?"checked":"unchecked"));

});

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String args[])

new CheckBoxExample();

}
}
Output:

Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from multiple
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 the button.

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 a) It is used to add the action listener to this object.

Java JRadioButton Example with ActionListener


import javax.swing.*;

import java.awt.event.*;

class RadioButtonExample extends JFrame implements ActionListener{

JRadioButton rb1,rb2;

JButton b;

RadioButtonExample(){

rb1=new JRadioButton("Male");

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

rb2=new JRadioButton("Female");

rb2.setBounds(100,100,100,30);

ButtonGroup bg=new ButtonGroup();

bg.add(rb1);bg.add(rb2);
b=new JButton("click");

b.setBounds(100,150,80,30);

b.addActionListener(this);

add(rb1);add(rb2);add(b);

setSize(300,300);

setLayout(null);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

public void actionPerformed(ActionEvent e){

if(rb1.isSelected()){

JOptionPane.showMessageDialog(this,"You are Male.");

if(rb2.isSelected()){

JOptionPane.showMessageDialog(this,"You are Female.");

public static void main(String args[]){

new RadioButtonExample();

}}
Output:
Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab with a
given title or icon. It inherits JComponent class.

JTabbedPane class declaration


Let's see the declaration for javax.swing.JTabbedPane class.
1. public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstant
s

Commonly used Constructors:


Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab


placement of JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab


placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab


tabLayoutPolicy) placement and tab layout policy.

Java JTabbedPane Example


import javax.swing.*;

public class TabbedPaneExample {


JFrame f;

TabbedPaneExample(){

f=new JFrame();

JTextArea ta=new JTextArea(200,200);

JPanel p1=new JPanel();

p1.add(ta);

JPanel p2=new JPanel();

JPanel p3=new JPanel();

JTabbedPane tp=new JTabbedPane();

tp.setBounds(50,50,200,200);

tp.add("main",p1);

tp.add("visit",p2);

tp.add("help",p3);

f.add(tp);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String[] args) {

new TabbedPaneExample();

}}
Output:

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
Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter, when


present, sets the scroll pane's client. The two int parameters,
when present, set the vertical and horizontal scroll bar policies
JScrollPane(Component (respectively).
)

JScrollPane(int, int)

JScrollPane(Component
, int, int)

Useful Methods
Modifier Method Description

void setColumnHeaderView(Compo It sets the column header for the scroll pane.
nent)
void setRowHeaderView(Component It sets the row header for the scroll pane.
)

void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and must
be one of the following constants defined in
Compone getCorner(String) ScrollPaneConstants: UPPER_LEFT_CORNER,
nt UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.

JScrollPane Example

import javax.swing.*;

public class ScrollPaneDemo extends JFrame

public ScrollPaneDemo() {

super("ScrollPane Demo");

ImageIcon img = new ImageIcon("E:\\501\\apple.jpg");

JScrollPane png = new JScrollPane(new JLabel(img));

getContentPane().add(png);

setSize(200,200);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}
public static void main(String[] args) {

new ScrollPaneDemo();

Output:

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.

JList class declaration


Let's see the declaration for javax.swing.JList class.
1. 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 specified
array.

JList(ListModel<ary> Creates a JList that displays elements from the specified,


dataModel) non-null, model.
Commonly used Methods:
Methods Description

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


addListSelectionListener(ListSelectionListene notified each time a change to the selection
r listener) 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.

import javax.swing.*;

import java.awt.event.*;

public class ListExample

ListExample(){

JFrame f= new JFrame();

final JLabel label = new JLabel();

label.setSize(500,100);

JButton b=new JButton("Show");

b.setBounds(200,150,80,30);

final DefaultListModel<String> l1 = new DefaultListModel<>();

l1.addElement("C");
l1.addElement("C++");

l1.addElement("Java");

l1.addElement("PHP");

final JList<String> list1 = new JList<>(l1);

list1.setBounds(100,100, 75,75);

DefaultListModel<String> l2 = new DefaultListModel<>();

l2.addElement("Turbo C++");

l2.addElement("Struts");

l2.addElement("Spring");

l2.addElement("YII");

final JList<String> list2 = new JList<>(l2);

list2.setBounds(100,200, 75,75);

f.add(list1); f.add(list2); f.add(b); f.add(label);

f.setSize(450,450);

f.setLayout(null);

f.setVisible(true);

b.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String data = "";

if (list1.getSelectedIndex() != -1) {

data = "Programming language Selected: " + list1.getSelectedValue();

label.setText(data);
}

if(list2.getSelectedIndex() != -1){

data += ", FrameWork Selected: ";

for(Object frame :list2.getSelectedValues()){

data += frame + " ";

label.setText(data);

});

public static void main(String args[])

new ListExample();

}}
Output:
Java 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.

JComboBox class declaration


Let's see the declaration for javax.swing.JComboBox class.
1. public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionLi
stener, Accessible

Commonly used Constructors:


Constructor Description

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

JComboBox(Object[] Creates a JComboBox that contains the elements in the


items) specified array.

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


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 the list.

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


editable.

void It is used to add the ActionListener.


addActionListener(ActionListener a)

void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox Example with ActionListener


import javax.swing.*;

import java.awt.event.*;

public class ComboBoxExample {

JFrame f;

ComboBoxExample(){

f=new JFrame("ComboBox Example");

final JLabel label = new JLabel();

label.setHorizontalAlignment(JLabel.CENTER);

label.setSize(400,100);

JButton b=new JButton("Show");

b.setBounds(200,100,75,20);

String languages[]={"C","C++","C#","Java","PHP"};

final JComboBox cb=new JComboBox(languages);


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

f.add(cb); f.add(label); f.add(b);

f.setLayout(null);

f.setSize(350,350);

f.setVisible(true);

b.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String data = "Programming language Selected: "

+ cb.getItemAt(cb.getSelectedIndex());

label.setText(data);

});

public static void main(String[] args) {

new ComboBoxExample();

}
Output:
Java Swing Menus
JMenuBar, JMenu and JMenuItem
The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull down menu component which is displayed 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.

Example of creating Edit menu for Notepad:


import javax.swing.*;
import java.awt.event.*;
public class MenuExample implements ActionListener{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
MenuExample(){
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");
edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
mb.add(file);mb.add(edit);mb.add(help);
ta=new JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args) {
new MenuExample();
}
}
Output:
Java AWT Dialog
The Dialog 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 Window class.
Unlike Frame, it doesn't have maximize and minimize buttons.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog
doesn't have.

AWT Dialog class declaration


1. public class Dialog extends Window

Java AWT Dialog Example


import java.awt.*;

import java.awt.event.*;

public class DialogExample {

private static Dialog d;

DialogExample() {

Frame f= new Frame();

d = new Dialog(f , "Dialog Example", true);

d.setLayout( new FlowLayout() );

Button b = new Button ("OK");

b.addActionListener ( new ActionListener()

public void actionPerformed( ActionEvent e )

DialogExample.d.setVisible(false);

});

d.add( new Label ("Click button to continue."));


d.add(b);

d.setSize(300,300);

d.setVisible(true);

public static void main(String args[])

new DialogExample();

}
Output:

Applets

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 platforms, 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).
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);
}

Note: class must be public because its object is created by Java Plugin software that resides on the browser.

myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and
compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing
purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}

}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Applets and HTML
Features of Applets over HTML
 Displaying dynamic web pages of a web application.
 Playing sound files.
 Displaying documents
 Playing animations

Security Issues

1. In general, applets loaded over the Internet (or any network) are prevented
from reading and writing files on the client file system, and from making
network connections except to the originating host.
2. Applets loaded over the net are prevented from starting other programs on
the client.
3. Applets are not allowed to open network connections to any computer,
except for the host that provided the .class files.
4. Applets loaded over the net are not allowed to start programs on the client.

Applets and Applications


Difference between Application and Applet:

Java Application Java Applet

Applications are just like a Java Applets are small Java programs that are
programs that can be execute designed to be included with the HTML
independently without using the web document. They require a Java-
web browser. enabled web browser for execution.

Application program requires a Applet does not require a main function for
main function for its execution. its execution.

Java application programs have the


full access to the local file system Applets don’t have local disk and network
and network. access.
Java Application Java Applet

Applets can only access the browser


Applications can access all kinds of specific services. They don’t have access
resources available on the system. to the local system.

Applications can executes the Applets cannot execute programs from the
programs from the local system. local machine.

An application program is needed


to perform some task directly for An applet program is needed to perform
the user. small tasks or the part of it.

passing parameters to applets

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.

import java.awt.*;
import java.applet.*;

/*
<applet code="Applet8" width="400"
height="200">
<param name="Name" value="Roger">
<param name="Age" value="26">
<param name="Sport" value="Tennis">
<param name="Food" value="Pasta">
<param name="Fruit" value="Apple">
<param name="Destination"
value="California">
</applet>
*/

public class Applet8 extends Applet


{
String name;
String age;
String sport;
String food;
String fruit;
String destination;

public void init()


{
name = getParameter("Name");
age = getParameter("Age");
food = getParameter("Food");
fruit = getParameter("Fruit");
destination = getParameter("Destination");
sport = getParameter("Sport");
}
public void paint(Graphics g)
{
g.drawString("Reading parameters passed to
this applet -", 20, 20);
g.drawString("Name -" + name, 20, 40);
g.drawString("Age -" + age, 20, 60);
g.drawString("Favorite fruit -" + fruit,
20, 80);
g.drawString("Favorite food -" + food, 20,
100);
g.drawString("Favorite destination -" +
name, 20, 120);
g.drawString("Favorite sport -" + sport,
20, 140);
}

}
Output
Creating a Swing Applet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JApplet
class extends the Applet class.

1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void init(){
8.
9. tf=new JTextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new JButton("Click");
13. b.setBounds(80,150,70,40);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is invoked
only once.

myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Painting in Swing:

Displaying graphics in swing:


java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with
the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to
draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill
oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw
line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to
the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font
to the specified font.
import java.awt.*;

import javax.swing.JFrame;

public class DisplayGraphics extends Canvas{

public void paint(Graphics g) {

g.drawString("Hello",40,40);

setBackground(Color.WHITE);

g.fillRect(130, 30,100, 80);

g.drawOval(30,130,50, 60);

setForeground(Color.RED);

g.fillOval(130,130,50, 60);

g.drawArc(30, 200, 40,50,90,60);

g.fillArc(30, 130, 40,50,180,40);

public static void main(String[] args) {

DisplayGraphics m=new DisplayGraphics();

JFrame f=new JFrame();

f.add(m);

f.setSize(400,400);

//f.setLayout(null);

f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

output

A Paint example

Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.

Example of Painting in Applet:


import java.awt.*;
1. import java.awt.event.*;
2. import java.applet.*;
3. public class MouseDrag extends Applet implements MouseMotionListener{
4.
5. public void init(){
6. addMouseMotionListener(this);
7. setBackground(Color.red);
8. }
9.
10. public void mouseDragged(MouseEvent me){
11. Graphics g=getGraphics();
12. g.setColor(Color.white);
13. g.fillOval(me.getX(),me.getY(),5,5);
14. }
15. public void mouseMoved(MouseEvent me){}
16.
17. }
In the above example, getX() and getY() method of MouseEvent is used to get the current x-
axis and y-axis. The getGraphics() method of Component class returns the object of Graphics.

myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

You might also like