0% found this document useful (0 votes)
37 views109 pages

23IT1301 - OOPs - Unit - 5

oops notes unit 5

Uploaded by

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

23IT1301 - OOPs - Unit - 5

oops notes unit 5

Uploaded by

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

23IT1301 – Object Oriented Programming – III Sem CSE 1

UNIT V GENERIC PROGRAMMING AND EVENT DRIVEN PROGRAMMING

Generic Programming – Generic classes – Generic methods – Bounded Types –


Restrictions and Limitations-Basics of event handling - event handlers - adapter classes -
actions - mouse and key events –AWT - Introduction to Swing – layout management -
Swing Components –Windows–Menus– Dialog Boxes.

5.1: Introduction to Generic Programming

Generic programming is a style of computer programming in which algorithms are written in


terms of ―to-be-specified-later” types that are then instantiated when needed for specific types
provided as parameters.
Generic programming refers to writing code that will work for many types of data.

NON-GENERICS:

In java, there is an ability to create generalized classes, interfaces and methods by operating
through Object class.

Example:

class NonGen
{
Object ob;
NonGen(Object o)
{
ob=o;
}
Object getob()
{
return ob;
}
void showType()
{
System.out.println("Type of ob is "+ob.getClass().getName());
}
}
public class NonGenDemo
{
public static void main(String[] arg)
{

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 2

NonGen integerObj;
integerObj=new NonGen(88);
integerObj.showType();
int v=(Integer)integerObj.getob(); // casting required
System.out.println("Value = "+v);
NonGen strObj=new NonGen("Non-Generics Test");
strObj.showType();
String str=(String)strObj.getob(); // casting required
System.out.println("Vlaue = "+str);
}
}

Output:

Type of ob is java.lang.Integer
Value = 88
Type of ob is java.lang.String
Vlaue = Non-Generics Test

Limitation of Non-Generic:
1) Explicit casts must be employed to retrieve the stored data.
2) Type mismatch errors cannot be found until run time.

Need for Generic:


1) It saves the programmers burden of creating separate methods for handling data
belonging to different data types.
2) It allows the code reusability.
3) Compact code can be created.

Advantage of Java Generics (Motivation for Java Generics):

1) Code Reuse: We can write a method/class/interface once and use for any type we want.
2) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to
store other objects.
3) Elimination of casts: There is no need to typecast the object.
The following code snippet without generics requires casting:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
When re-written to use generics, the code does not require casting:
List<String> list = new ArrayList<String>();
list.add("hello");
Panimalar Enginerring College Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 3

String s = list.get(0);
4) Stronger type checks at compile time:
A Java compiler applies strong type checking to generic code and issues errors if the
code violates type safety. Fixing compile-time errors is easier than fixing runtime errors,
which can be difficult to find.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32); //Compile Time Error

5) Enabling programmers to implement generic algorithms.


By using generics, programmers can implement generic algorithms that work on
collections of different types, can be customized, and are type safe and easier to read.

5.2: GENERIC CLASSES

A class that can refer to any type is known as generic class. Here, we are using T type
parameter to create the generic class of specific type.

A generic class declaration looks like a non-generic class declaration, except that the class
name is followed by a type parameter section.

Where, the type parameter section, delimited by angle brackets (<>), follows the class name. It
specifies the type parameters (also called type variables)
Example:
public class Pair<T, S>
{
...
}
Panimalar Enginerring College Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 4

Purpose: To define a generic class with methods and fields that depends on type variables.

Class reference declaration:


To instantiate this class, use the new keyword, as usual, but place <type_parameter>
between the class name and the parenthesis:

class_name<type-arg-list> var-name=new class_name<type-arg-list>(cons-arg-list);

Type Parameter Naming Conventions:

 Type parameter is a place holder for a type argument.


 By convention, type parameter names are single, uppercase letters.

The most commonly used type parameter names are:

 E - Element (used extensively by the Java Collections Framework)


 K - Key
 N - Number
 T - Type
 V - Value
 S,U,V etc. - 2nd, 3rd, 4th types

Example: Generic class with single type parameter


class Gen <T>
{
T obj;
Gen(T x)
{
obj= x;
}

T show()
{
return obj;
}

void disp()
{
System.out.println(obj.getClass().getName());
}
}

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 5

public class Test


{
public static void main (String[] args)
{
Gen < String> ob = new Gen<>("java programming with Generics");
ob.disp();
System.out.println("value : " +ob.show());

Gen < Integer> ob1 = new Gen<>(550);


ob1.disp();
System.out.println("value :" +ob1.show());
}
}

Output:
java.lang.String
value : java programming with Generics
java.lang.Integer
value :550

Example: Generic class with more than one type parameter

In Generic parameterized types, we can pass more than 1 data type as parameter. It works the
same as with one parameter Generic type.

class Gen <T1,T2>


{
T1 obj1;
T2 obj2;
Gen(T1 o1,T2 o2)
{
obj1 = o1;
obj2 = o2;
}
T1 get1()
{
return obj1;
}
T2 get2()
{
return obj2;
Panimalar Enginerring College Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 6

}
void disp()
{
System.out.println(obj1.getClass().getName());
System.out.println(obj2.getClass().getName());
}
}

public class Test


{
public static void main (String[] args)
{
Gen < String, Integer> obj = new Gen<>("java programming with Generics",560);
obj.disp();
System.out.println("value 1 : " +obj.get1());
System.out.println("value 2: "+obj.get2());

Gen < Integer, Integer> obje = new Gen<>(1000,560);


obje.disp();
System.out.println("value 1 : " +obje.get1());
System.out.println("value 2: "+obje.get2());
}
}

Output:
java.lang.String
java.lang.Integer
value 1 : java programming with Generics
value 2: 560

java.lang.Integer
java.lang.Integer
value 1 : 1000
value 2: 560

5.3: GENERIC METHODS

A Generic Method is a method with type parameter. We can write a single generic method
declaration that can be called with arguments of different types. Based on the types of the
arguments passed to the generic method, the compiler handles each method call
appropriately.

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 7

Rules to define Generic Methods


 All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type.
 Each type parameter section contains one or more type parameters separated by
commas. A type parameter, also known as a type variable, is an identifier that specifies
a generic type name.
 The type parameters can be used to declare the return type and act as placeholders for
the types of the arguments passed to the generic method, which are known as actual
type arguments.
 A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double and
char).

Example:
class Main {
public static void main(String[] args) {

// initialize the class with Integer data


DemoClass demo = new DemoClass();

// generics method working with String


demo.<String>genericsMethod("Java Programming");

// generics method working with integer


demo.<Integer>genericsMethod(25);
}
}

class DemoClass {

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 8

// creae a generics method


public <T> void genericsMethod(T data) {
System.out.println("Generics Method:");
System.out.println("Data Passed: " + data);
}
}

Example: (To iterate through the list and display the element using generic method)

class a < T >


{
<T> void show(T[] el)
{
for(T x:el)
System.out.println(x);
}
}

public class GenMethod


{
public static void main(String arg[])
{
System.out.println("Integer array");
a<Integer> o1=new a<Integer>();
Integer[] ar={10,67,23};
o1.show(ar);

System.out.println("String array");
a<String> o2=new a<String>();
String[] ar1={"Hai","Hello","Welcome","to","Java programming"};
o2.show(ar1);

System.out.println("Boolean array");
a<Boolean> o3=new a<Boolean>();
Boolean[] ar2={true,false};
o3.show(ar2);

System.out.println("Double array");
a<Double> o4=new a<Double>();
Double[] ar3={10.234,67.451,23.90};
o4.show(ar3);
}
Panimalar Enginerring College Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 9

}
Output:

Integer array
10
67
23
String array
Hai
Hello
Welcome
to
Java programming
Boolean array
true
false
Double array
10.234
67.451
23.9

5.4: GENERICS WITH BOUNDED TYPES

5.4.1: GENERICS WITH BOUNDED TYPE PARAMETERS:

Bounded Type Parameter is a type parameter with one or more bounds. The bounds
restrict the set of types that can be used as type arguments and give access to the methods
defined by the bounds.
For example, a method that operates on numbers might only want to accept instances of
Number or its subclasses.

Syntax:
<T extends superclass>

Example:

The following example creates a generic class that contains a method that returns the
average of array of any type of numbers. The type of the numbers is represented generically
using Type Parameter.

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 10

public class GenBounds<T extends Number>


{
T[] nums;
GenBounds(T[] obj)
{
nums=obj;
}
double average()
{
double sum=0.0;
for(int i=0;i<nums.length;i++)
sum+=nums[i].doubleValue();
double avg=sum/nums.length;
return avg;
}
public static void main(String[] args)
{
Integer inum[]={1,2,3,4,5};
GenBounds<Integer> iobj=new GenBounds<Integer>(inum);
System.out.println("Average of Integer Numbers : "+iobj.average());

Double dnum[]={1.1,2.2,3.3,4.4,5.5};
GenBounds<Double> dobj=new GenBounds<Double>(dnum);
System.out.println("Average of Double Numbers : "+dobj.average());

/* Error: java,lang.String not within bound


String snum[]={"1","2","3","4","5"};
GenBounds<String> sobj=new GenBounds<String>(snum);
System.out.println("Average of Integer Numbers : "+iobj.average()); */
}
}

Output:
F:\>java GenBounds
Average of Integer Numbers : 3.0
Average of Double Numbers : 3.3

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 11

5.5: RESTRICTIONS AND LIMITATIONS OF GENERICS

1) In Java, generic types are compile time entities. The runtime execution is possible only
if it is used along with raw type.
2) Primitive type parameters are not allowed for generic programming.
For example:
Stack<int> is not allowed.
3) For the instances of generic class throw and catch keywords are not allowed.
For example:
public class Test<T> extends Exception
{
// code// Error: can’t extend the Exception class
}
4) Instantiation of generic parameter T is not allowed.
For Example:
new T();// Error
new T[10];// Error
5) Arrays of parameterized types are not allowed.
For Example:
New Stack<String>[10];// Error

5.6: GRAPHICS PROGRAMMING

Graphics in any language gives a wonderful look and feel to the users as well as
programmers. Programmers draw figures, strings etc with the help of graphics. Without
graphics the windows programming is incomplete. Java is not behind. Java provides Abstract
Window Toolkit (AWT) to develop graphical applications.

Definition: AWT
AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating Graphical
User Interface (GUI) for java programs 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.

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 12

JAVA AWT CLASS HIERARCHY


The hierarchy of Java AWT classes is given below.
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.

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 13

Component & Window class Methods:


java.awt.Component

 void setVisible(boolean b) - shows or hides the component depending on whether b


is true or false.
 void setSize(int width, int height) - resizes the component to the specified width
and height.
 void setBounds(int x, int y, int width, int height) - moves and resizes this component.
The location of the top-left corner is given by x and y, and the new size is given by
the width and height parameters.
 void setBackground(java.awt.Color) – set Background color to the window.
 void setForeground(java.awt.Color)- set Foreground color to the window.
 void repaint() - causes a repaint of the component ―as soon as possible.

java.awt.Window
 void setTitle(String s) - sets the text in the title bar for the frame to the string s.

5.7: FRAMES

Definition: Frame
Frame is a top-level window that has a title bar, menu bar, borders, and resizing corners.
By default, a frame has a size of 0 × 0 pixels and it is not visible.
Frames are examples of containers. It can contain other user interface components such
as buttons and text fields.

Constructors of Frame (java.awt.Frame class)

Constructor Description
public Frame() Creates a Frame window with no name.
public Frame(String name) Creates a Frame window with a name.

Frame methods

Methods Description
This method adds the component, comp, to the
public void add(Component comp)
container Frame.
public void setLayout(LayoutManager This method sets the layout of the components in a
object) container, Frame.

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 14

This method removes a component, comp, from the


public void remove(Component comp)
container, Frame.
public void setSize(int widthPixel, int This method sets the size of a Frame in terms of
heightPixel) pixels.

CREATING FRAMES IN AWT

To create simple awt application, 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)

Method 1: By Extending Frame class (Inheritance)

 Create a subclass of Frame.


 In the Subclass constructor
o Change the frame title by calling superclass [Frame] constructor using
super(String) method call.
o Set the size of the window explicitly by calling the setSize( ) method.
o Make the frame visible by calling setVisible() method.
 In main() method
o Create an instance of subclass. Example:

The following java program creates a frame with the dimension as 600 x 400 and
makes it visible in the screen. Import java.awt package because Frame class is available in
that package.

import java.awt.*;
public class Demo extends Frame
{
Demo(String s)
{
super(s);
setSize(600,400);
setVisible(true);
}
public static void main(String arg[])
{
Demo ob=new Demo("Demo");
}
}

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 15

Method 2: By creating the object of Frame class (Association)

 Create an instance of a Frame class.


 Frame f=new Frame(― frame name‖);
 Set the frame size
 f.setSize(500,500);
 Make the frame visible
 f.setVisible(true);
Example:
The following java program creates a frame with the dimension as 600 x 400 and
makes it visible in the screen. Import java.awt package because Frame class is available in
that package.

import java.awt.*;
public class Demo{
public static void main(String arg[])
{
Frame f=new Frame("Demo");
f.setSize(600,400);
f.setVisible(true);
}

5.8: AWT COMPONENTS


There are various graphical components that can be placed on the frame.
 The components classes have the corresponding methods.
 All components are subclass of Component class. Components allow the user to interact
with application. A layout manager arranges components within a container
(Frame/Applet/Panel).

Adding and Removing Controls:


 add(Component compObj)- add components to the conatainer. Once it is added, it will
automatically be visible whenever its parent window is displayed. Here, compObj is an
instance of the control that you want to add.
 void remove(Component obj)- remove a control from a window
 removeAll( )- remove all controls from a window
Component Constructor Methods

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 16

Label  Label( )  void setText(String str)


 Label(String str)  String getText( )
 Label(String str, int how)
Button  Button( )  void setLabel(String str)
 Button(String str)  String getLabel( )

List  List( )  void add(String name)


 List(int numRows)  void add(String name, int
 List(int numRows, boolean multipleSelect) index)
 String getSelectedItem( )
 int getSelectedIndex( )
 String[ ] getSelectedItems( )

Choice  Choice( )  void add(String name)


 String getSelectedItem( )
 int getSelectedIndex( )

Checkbox  Checkbox( )  boolean getState( )


 Checkbox(String str)  void setState(boolean on)
 Checkbox(String str, boolean on)  String getLabel( )
 Checkbox(String str, boolean on,  void setLabel(String str)
CheckboxGroup cbGroup)
 Checkbox(String str, CheckboxGroup cbGroup,
boolean on)
TextField  TextField( )  String getText( )
 TextField(int numChars)  void setText(String str)
 TextField(String str)  void setEditable(boolean
 TextField(String str, int numChars) canEdit)

TextArea  TextArea( )  void append(String str)


 TextArea(int numLines, int numChars)  void insert(String str, int
 TextArea(String str) index)
 TextArea(String str, int numLines, int
numChars)

Scrollbars  Scrollbar( )  int getMinimum( )


 Scrollbar(int style)  int getMaximum( )
 Scrollbar(int style, int initialValue, int  void setValues(int
thumbSize, int min, int max) initialValue, int thumbSize,
int min, int max)

AWT supports the following types of controls:

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 17

1. Labels
2. Push buttons
3. Check Boxes
4. Choice Lists
5. Lists
6. Scroll bars
7. Text Components

1: Label:
 The easiest control to use is a Label.
 A label is an object of type Label, and it contains string to display.
 Labels are passive controls that do not support any interaction with the user.

Constructors:
1. Label() - creates a blank label
2. Label(Stirng str) - creates a label that contains a string
3. label(String str, int style) - creates a label with specified string and alignment.
The value of style must be one of these three constants:
Label.LEFT, Label.RIGHT or Label.CENTER
Example:

import java.awt.*;
public class Use_Label {
public static void main(String[] args) {
Frame fr=new Frame(" This program is for displaying Label");
fr.setSize(400,200);
fr.setLayout(new FlowLayout());
fr.setVisible(true);
Label l1=new Label("OK");
Label l2=new Label("CANCEL");
fr.add(l1);
fr.add(l2); } }

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 18

2. Buttons:
 Most widely used control is Button or Push Buttons.
 A Button is a component that contains a label and that generates an event when it is
pressed.
Constructors:
1. Button() - creates an empty Button
2. Button(String str) - creates a button that contains str as label.

Example:

import java.awt.*;
public class Use_Button
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Buttons");
fr.setSize(400,200);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Button B1=new Button();
B1.setLabel("Ok");
Button B2=new Button("CANCEL");
Button button[]=new Button[3];
String colors[]={"Red","Blue","Green"};
for(int i=0;i<button.length;i++)
{
button[i]=new Button(""+colors[i]);
fr.add(button[i]);
}
fr.add(B1);
fr.add(B2);
}
}

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 19

3. Check Boxes:
 A check box is a control that is used to turn an option on or off.
 It consists of a small box that can either contain a check mark or not.
 There is a label associated with each check box that describes what option the box
represents. We can change the state of the check box by clicking on it.
Constructors:
1. Checkbox() - creates a check box with blank label
2. Checkbox(String str) - creates a check box with specified string
3. Checkbox(String str, boolean on) - creates a checkbox with initial state as On and with
the specified string.

Example:

import java.awt.*;

public class Use_Checkbox


{
public static void main(String[] args)
{
Frame fr=new Frame("Using Check Boxes");
fr.setLayout(new FlowLayout());
fr.setSize(500,300);
fr.setVisible(true);
Label l1=new Label("Select Your favourite games");
Checkbox chk1=new Checkbox("Cricket");
Checkbox chk2=new Checkbox("Foot Ball");
Checkbox chk3=new Checkbox("Hocky");
fr.add(l1);
fr.add(chk1);
fr.add(chk2);
fr.add(chk3);
}
}

Output:

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 20

4. Choice:
 The choice class is used to create a pop-up list of items from which the user may
choose.
 When inactive, it shows up only the selected item. When the user clicks on it, the whole
list of choices pops up and the new selection can be made.
 It is single-choice selection list.

Constructors:
Choice only defines the default constructor, which creates an empty list.
Adding items to the list:
To add items to the list, use add() method.
void add(String str)
Example:
import java.awt.*;
public class Use_Choice
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Choice List");
fr.setVisible(true);
fr.setSize(300,300);
fr.setLayout(new FlowLayout());
Label l1=new Label("Choose your favourite Game:");
Choice ch=new Choice();
ch.add("Cricket");
ch.add("Foot Ball");
ch.add("Hocky");
ch.add("kabadi");
ch.add("kho-kho");
fr.add(l1);
fr.add(ch);

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 21

}
}

Output:

5. Lists:
 The list class provides a compact, multiple-choice, scrolling selection list.
 Unlike the Choice object, which shows only the selected item in the menu, a List
object can be constructed to show any number of choices in the visible window.
 It is created to allow multiple selections.
Constructors:
1. List() - creates a List control that allows only one item to be selected at any one time.
2. List(int numRows) - creates a list with the specified number of entries. The numRows
specifies the number of entries in the list that will always be visible (others can be scrolled into
view as needed).
3. List(int numRows, Boolean multipleSelect) - In this, if multipleselect is true, then the
user may select two or more items at a time. If it is false , then only one item may be selected.
Example:
import java.awt.*;
public class Use_List
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Choice List");
fr.setVisible(true);
fr.setSize(300,300);
fr.setLayout(new FlowLayout());
Label l1=new Label("Choose your favourite Game:");
List ls=new List(7, true);
ls.add("Cricket");
ls.add("Foot Ball");
ls.add("Hocky");
ls.add("kabadi");
Panimalar Enginerring College Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 22

ls.add("kho-kho");
fr.add(l1);
fr.add(ls);
}

}
Output:

6. Scroll Bars:
 Scroll bars can be represented by the slider widgets.
 Scroll bars are used to select continuous values between a specified minimum and
maximum.
 Two types: Horizontal scroll bar and Vertical Scroll bar
Constructors:
1. Scrollbar() - creates a vertical scroll bar
2. Scrollbar(int style)
3. Scrollbar(int style, int initialvalue, int thumbsize, int min, int max)

Example:
import java.awt.*;
public class Use_Scrollbar {
public static void main(String[] arg)
{
Frame fr=new Frame("Using Choice List");
fr.setVisible(true);
fr.setSize(300,300);
fr.setLayout(new FlowLayout());
Scrollbar horzSB=new Scrollbar(Scrollbar.HORIZONTAL,0,1,1,300);
Scrollbar vertSB=new Scrollbar();
fr.add(horzSB);
fr.add(vertSB);
}

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 23

Output:

7. Text Components:
There are two classes under Text Components:
1. TextField
2. TextArea

1. TextArea:
 The TextField is a slot in which one line text can be entered.
 In the TextField, we can enter the string, modify it, copy, cut or paste it.
 TextField is a subclass of TextComponent.
Constructors:
1. TextField() - creates a default text field.
2. TextField(int numChars) - creates a text field of specified characters wide.
3. TextField(String str) - creates a text field with the default string str.
4. TextField(String str, int numChars)

2. TextArea:
 The TextArea control is used to handle multi-line text and it is called as Multiline
Editor.

Constructors:
1. TextArea()
2. TextArea(int numLines, int numChars)
3. TextArea(String str)
4. TextArea(String str, int numLines, int numChars, int sBars)
Panimalar Enginerring College Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 24

Here,
numLines – specifies the height, in lines, of the text area
numChars – specifies width of the text area
str – specifies the initial text
sBar – specifies the Scroll Bars. It must be one of the following values:
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
Example: (TextField and TextArea)

import java.awt.*;
public class Use_TextComponent
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Text Components");
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Label l1=new Label("Enter Your Name: ");
TextField tf=new TextField("AAA",30);
fr.add(l1);
fr.add(tf);
Label l2=new Label("Enter Your Address: ");
TextArea ta=new TextArea("Chennai",10,20);
fr.add(l2);
fr.add(ta);
}
}

Output:

8. Canvas:

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 25

 Canvas is special area created on the frame.


 The canvas is specially used for drawing the graphical components such as oval,
rectangle, line and so on.
Methods:
1. void setSize(int width, itn height) - sets the size of the canvas fro given width and
height.
2. void setBackground(Color c) - sets the background color of the canvas.
3. void setForeground(Color c) - sets the color for the text.

Example:
import java.awt.*;
public class Use_Canvas
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Canvas");
fr.setSize(250,250);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Canvas c1=new Canvas();
c1.setSize(120,120);
c1.setBackground(Color.YELLOW);
c1.setForeground(Color.GREEN);
fr.add(c1);
}
}

5.9: WORKING WITH 2D SHAPES GRAPHICS

 java.awt.Graphics Class:
 The Graphics class is part of the java.awt package.
 The Graphics class defines a number of drawing functions. Each shape can be drawn
edge-only or filled.
 Objects are drawn and filled in the currently selected graphics color, which is black by
default.
 When a graphics object is drawn that exceeds the dimensions of the window, output is
automatically clipped.
Java Coordinate System:
Java’s coordinate system has the origin (0, 0) in the top left corner.
Positive x values are to the right, and positive y values are down.
Coordinate units are measured in pixels (picture element). All pixel values are integers;

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 26

there are no partial or fractional pixels.

X coordinate: Horizontal distance moving right from the left of the screen.
Y coordinate: Vertical distance moving from top to bottom of the screen.
The Graphics class provides a set of simple built-in graphics primitives for drawing shapes
including lines, rectangles, polygons, ovals, and arcs.

1. Lines:
To draw straight lines, use the drawLine() method.
drawLine() method takes four arguments:
 the x and y coordinates of the starting point and
 the x and y coordinates of the ending point.
Method:
 void drawLine(int startX, int startY, int endX, int endY) - displays a line in the
current drawing color that begins at startX,startY and ends at endX,endY.

2. Rectangles:
 The Java graphics primitives provide two kinds of rectangles:
1.Plain rectangles and
2.Rounded rectangles(which are rectangles with rounded corners).
 The drawRect() and fillRect() methods displays an outlined and filled rectangle.
Methods:
 void drawRect(int x, int y, int width, int height)
 void fillRect(int x, int y, int width, int height)
 void drawRoundRect(int x, int y, int width, int height, int xDiam, int yDiam)
 void fillRoundRect(int x, int y, int width, int height, int xDiam, int yDiam)

 A rounded rectangle has rounded corners.


 The upper-left corner of the rectangle is at x, y.
 The dimensions of the rectangle are specified by width and height.
 The diameter of the rounding arc along the X axis is specified by xDiam.

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 27

 The diameter of the rounding arc along the Y axis is specified by yDiam.

3. Polygons:
 Polygons are shapes with an unlimited number of sides.
 Set of x and y coordinates are needed to draw a polygon, and the drawing method starts
at one, draws a line to the second, then a line to the third, and so on.
Methods:
 void drawPolygon(int x[ ], int y[ ], int numPoints)
 void fillPolygon(int x[ ], int y[ ], int numPoints)
Where,
x[]- An array of integers representing x coordinates
y[]- An array of integers representing y coordinates
numPoints- An integer for the total number of points

4. Oval:
To draw circle and ellipse, we can use the method drawOval().
Methods:
 void drawOval(int top, int left, int width, int height)
 void fillOval(int top, int left, int width, int height)

5. Arcs:
 Arcs can be drawn with drawArc() and fillArc() methods.
 The arc is drawn from startAngle through the angular distance specified by
sweepAngle.
 Angles are specified in degrees.
 The arc is drawn counterclockwise if sweepAngle is positive, and clockwise if arkAngle
is negative.

Methods:

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 28

 void drawArc(int x, int y, int width, int height, int startAngle, int sweepAngle)
 void fillArc(int x, int y, int width, int height, int startAngle, int sweepAngle)

JAVA 2D LIBRARY
 Java 2D library organizes geometric shapes in an object-oriented fashion. Following classes
are used to draw lines, rectangles, and ellipses:
 Line2D
 Rectangle2D
 Ellipse2D
 To draw shaped in the Java 2D library,
1. First create an object of a class the Graphics2D class (subclass of Graphics class).
2. Call the draw() method of the Graphics2D class.

 Coordinate Specifications:
The Java 2D shapes use single-precision floating-point coordinates to draw shapes.

Methods of 2DShapes: Available in java.awt.geom package

Shapes Methods
Line2D Line2D.Double()
Line2D.Double(float x1,float y1, float x2, float y2)
Rectangle2D Rectangle2D.Double()
Rectangle2D.Double(double x, double y, double w, double h)
Rectangle2D.Float()
Rectangle2D.Float(float x, float y, float w, float h)
Ellipse2D Ellipse2D.Double()
Ellipse2D.Double(double x, double y, double w, double h)
Ellipse2D.Float()
Ellipse2D.Float(float x, float y, float w, float h)

Example: // Drawing 2D shapes using Graphics class & Graphics2D Library //

import java.awt.*;
import java.awt.geom.*;
public class Test_TwoDShapes extends Frame
{
Test_TwoDShapes(String s)
{
super(s);
setBounds(200,200,800,800);

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 29

setVisible(true);
}
public void paint(Graphics g)
{
g.drawString("2D shapes - Graphics Class",60,60);
g.drawString("Line", 80,100);
g.drawLine(120,100,180,100);
g.drawString("Rectangle", 80, 150);
g.drawRect(170,150,40,20);
g.fillRect(220,150,40,20);
g.drawString("Rounded Rectangle", 80,200);
g.drawRoundRect(200,200,50,50,10,10);
g.fillRoundRect(260,200,50,50,10,10);
g.drawString("Polygon", 80,270);
int x[]={270,350,290,220};
int y[]={350,290,310,270};
g.drawPolygon(x,y,4);
g.fillPolygon(x,y,4);
g.drawString("Oval", 80,370);
g.drawOval(100,370,40,40);
g.fillOval(160,370,40,40);
g.drawString("Arc", 80,450);
g.drawArc(120,450,70,70,0,180);
g.fillArc(190,450,70,70,0,180);

Graphics2D g2d=(Graphics2D)g;
g2d.setPaint(Color.RED);
g2d.drawString("2D Shapes - Graphics2D Library", 500,60);
g2d.draw(new Line2D.Double(500,100,550,100));
g2d.drawString("Line2D", 560,100);
g2d.fill(new Rectangle2D.Double(500,150,70,70));
g2d.drawString("Rectangle2D",590,150);
g2d.draw(new Ellipse2D.Float(500,250,60,40));
g2d.drawString("Ellipse2D", 630,250);

}
public static void main(String arg[])
{
Test_TwoDShapes ob=new Test_TwoDShapes("Line Demo");
}
}

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 30

Output:

5.10: USING COLOR, FONTS, AND IMAGES COLOR


5.10.1: USING COLOR:
java.awt.Color
The class java.awt.Color provides 13 standard colors as named-constants.
 Color class creates a solid RGB color with the specified red, green, blue value in the
range (0- 255).
 Java’s abstract color model uses 24-bit color. The values of each color must be in the
range (0- 255).
Constructor:
 Color(int red, int green, int blue) - create new color object for any combination of
red, green, and blue.
 Java.awt.Color class used to create new color object for any combination of red, green,
and blue, and it predefines a few color constants. They are stored in class variables,
Color.white (255,255,255) Color.cyan( 0,255,255)
Color.black (0,0,0) Color.pink (255,175,175)
Color.lightGray (192,192,192) Color.orange (255,200,0)
Color.gray (128,128,128)
Color.darkGray (64,64,64)
Color.red (255,0,0)
Color.green(0,255,0)
Color.blue (0,0,255)
Color.yellow (255,255,0)
Color.magenta (255,0,255)

Panimalar Enginerring College Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 26

Mehtods:
S.
Method Name Class Name Description
No
1 void setBackground(Color c) Sets the background color to the
java.awt.Component window
2 Color getBackground() Gets the background color of the
window
3 void setForeground(Color c) Sets the foreground color to the
window
4 Color getForeground() Gets the foreground color of the
window
5 Color getColor() Gets the current color of the graphics
java.awt.Graphics context
6 void setColor(Color c) Sets the new color to the graphics
context
7 Paint getPaint() Gets the paint property of the graphics
context
8 void setPaint(Paint P) java.awt.Graphics2D Sets the paint property of the graphics
context
9 void fill(Shape s) Fills the shape with current paint

Example:
import java.awt.*;
public class ColorDemo extends Frame
{
ColorDemo(String s)
{
super(s);
setSize(300,300);
setVisible(true);
setBackground(Color.lightGray);
setForeground(Color.BLUE);
}
public void paint(Graphics g)
{
int rval, gval, bval;
g.drawString("Color Demo", 120, 50);
for (int j = 80; j < 250-30; j += 30)
for (int i = 80; i < 250-30; i+= 30)
{
rval = (int)Math.floor(Math.random() * 256);
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 27

gval = (int)Math.floor(Math.random() * 256);


bval = (int)Math.floor(Math.random() * 256);
g.setColor(new Color(rval,gval,bval));
g.fillRect(i,j,25,25);
}
}
public static void main(String[] arg)
{
ColorDemo cd=new ColorDemo("Using Colors");
}
}
Output:

5.10.2: TEXT AND FONTS

The java.awt.Font class is used to create Font object to set the font for drawing text,
labels, text fields, buttons etc.,
Constructor:
 Font(String fontName, int fontStyle, int pointSize)
 Here, fontName specifies the name of the desired font. The style of the font is
specified by fontStyle. It may consist of one or more of these three constants:
Font.PLAIN, Font.BOLD, and Font.ITALIC. The size, in points, of the font is
specified by pointSize. point size may or may not be the height of the characters.
 To draw characters in a font:
1. First create an object of the class Font.
2. Then specify the font name, the font style, and the point size.

Methods:
Method Description
String getFontName() Returns the font face name of this font
String getFamily() Returns the family name of this font
String getName() Returns the logical name of this font
void setFont(Font fontObj) selects a font for the graphics context. That font will be
used for subsequent text drawing operations
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 28

Example:
import java.awt.*;
public class FontDemo extends Frame
{
FontDemo(String s)
{
super(s);
setSize(600,600);
setVisible(true);
}
public void paint(Graphics g)
{
int k=0;
Font f = new Font("TimesRoman", Font.PLAIN, 18);
Font fb = new Font("Monotype Corsiva", Font.BOLD, 18);
Font fi = new Font("Calibri", Font.ITALIC, 18);
Font fbi = new Font("TimesRoman", Font.BOLD + Font.ITALIC, 18);
g.setFont(f);
g.drawString("This is a plain font", 10, 50);
g.setFont(fb);
g.drawString("This is a bold font", 10, 75);
g.setFont(fi);
g.drawString("This is an italic font", 10, 100);
String msg;
msg=" Current Font Name: "+fi.getName();
g.drawString(msg, 10, 120);
msg=" Current Font Style: "+fi.getStyle();
g.drawString(msg, 10, 140);
msg=" Current Font Size: "+fi.getSize();
g.drawString(msg, 10, 160);
g.setFont(fbi);
g.drawString("This is a bold italic font", 10, 180);
g.drawString("List of Available Fonts", 400, 10);
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts=ge.getAvailableFontFamilyNames();
for(int i=20;i<40;i++)
{
g.drawString(fonts[i], 400, 20+k);
k=k+20;
}
}
public static void main(String arg[])
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 29

{
FontDemo ob=new FontDemo("Font Demo");
}
}
Output:

5.10.3: USING IMAGES

java.awt.Image:
Image class provides support for displaying and manipulation of graphical images. Image is
simply a rectangular graphical object.
Java provides the functions for reading images that are stored in local files and display them on
graphics object.

Step1: Loading an image:


 Method 1: Using java.awt.Toolkit
Toolkit getDefaultToolkit()- returns the default toolkit.
Image getImage(String filename) - returns an image that will read its pixel data from
a file.
Toolkit object can only read GIF and JPEG files.

 Method 2: Using javax.imageio


 ImageIO.read(new File(image_url)); - returns an image. This method throws an
IOException if the image is not available.

Step2: displaying an image java.awt.Graphics


 boolean drawImage(Image img, int x, int y, ImageObserver observer)- draws a scaled
image.
 boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver
observer) - draws a scaled image.

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 30

The system scales the image to fit into a region with the given width and height.

Example:
The following program draws a tiled graphics image from the top-left corner to bottom right
corner of the window.

import java.awt.*;
import java.io.*;
import javax.imageio.*;
public class ImageDemo extends Frame
{
ImageDemo(String s)
{
super(s);
setSize(400,400);
setLocation(600,400);
setBackground(Color.yellow);
setVisible(true);
setForeground(Color.BLUE);
}
public void paint(Graphics g)
{
Image img = null;
try
{
img=ImageIO.read(new File("F:/icon.png"));
}
catch(IOException e)
{
e.printStackTrace();
}
for (int i = 0; i <400; i=i+20)
for (int j = 0; j <400; j=j+20)
g.drawImage(img,i,j,null);
g.drawString("Hello", 350, 350);
}
public static void main(String arg[])
{
ImageDemo ob=new ImageDemo("Image Demo");
}
}

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 31

Output:

5.11: BASICS OF EVENT HANDLING

Definition: Event
Changing the state of an object is known as an event. i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page are the activities that causes
an event to happen.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism has the code which is known as event handler that is executed
when an event occurs.

Events are included in the following packages:


1) java.util
2) java.awt
3) java.awt.event

DELEGATION EVENT MODEL


Delegation Event Model is the modern approach to handle the event. It defines the standard
and consistent mechanism to generate and process events.
Concept:
 A source generates an event and sends it to one or more listeners.
 Listener simply waits until it receives an event.
 Once received, the listener processes the event and then returns.
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 32

 User interface element is able to "delegate" the processing of an event to a separate


piece of code.
 Notifications are sent only to those listeners that want to receive them.

 The Delegation Event Model is based on the concept of “Event source” and “Event
Listeners”
 Any object that is interested in receiving messages (or events) is called an Event
Listener.
 Any object that generates the messages (or Events) is called an Event Source.

COMPONENTS OF DELEGATION EVENT MODEL:

There are three major components in the delegation event model:


1. Events
2. Event Sources
3. Event Listeners

1. Events
An event is an object that describes a state change in a source. 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.

2. Event Sources
A Event Source is an object that generates an event. 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.

3. Event Listeners
Listener is an object that is notified when an event occurs. It has two major requirements:
1. It must have been registered with one or more sources to receive notifications about
specific types of events.
2. It must implement methods to receive and process these notifications.
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 33

Event Event Description Event Listener


Source
ActionEvent Button Generates action events when the ActionListener
button is pressed.
ItemEvent Checkbox Generates item events when the check ItemListener
box is selected or deselected.
ItemEvent Choice Generates item events when the ItemListener
choice is changed.
ItemEvent List Generates action events when an ItemListener
item is double-clicked;
MouseEvent Mouse Generates Mouse events when Mouse MouseListener
events when an item is selected or
input occurs.
deselected.
KeyEvent Keyboard Generates Key events when keyboard KeyListener
input occurs.

The package java.awt.event defines several types of events that are generated by various user
interface elements.

WORKING OF EVENT HANDLING


The following steps give an overview of how event handling in the AWT works:
1. A listener object is an instance of a class that implements a special interface called
(naturally enough) a listener interface.
2. An event source is an object that can register listener objects and send them event
objects.
3. The event source sends out event objects to all registered listeners when that event
occurs.
4. The listener objects will then use the information in the event object to determine their
reaction to the event.

You register the listener object with the source object by using lines of code that follow the
model:
eventSourceObject.addEventListener(eventListenerObject);
Example:
Button b1=new Button(―OK‖);
B1.addActionListener(this);
The listener object is notified whenever an ―action event‖ occurs on the button (when the
button is clicked).

The below figure explains the working of Delegation Event Model:

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 34

Advantages of Event Delegation Model:


1. In event delegation model, the events are handled using objects. This allows a clear
separation between the usage of the components and the design.
2. It accelerates the performance of the application in which multiple events are used.

5.12: AWT EVENT HIERARCHY

 Event handling in Java is object oriented, with all events descending from EventObject
class in the java.util.package.
 The EventObject class has a subclass AWTEvent, which is the parent of all AWT event
classes.
 The following diagram shows the hierarchy of AWT event class:

AWT Event Classes:

 AWT Event is the subclass of EventObject class.


 The subclasses of AWT Event class can be categorized into two:
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 35

1. Semantic Events
2. Low-level Events

1. Semantic Events:
A semantic event is one that expresses what the user is doing, such as ―clicking the button‖.
The following event classes are semantic event classes:
1. ActionEvent
2. AdjustmentEvent
3. ItemEvent
4. TextEvent

2. Low-level Events:
Low-level events are those that makes the semantic events possible. For example, a semantic
event ―button click‖ involves series of low level events such as mouse down, mouse moves and
a mouse up.
The following event classes are Low-level event classes:
1. ComponentEvent
2. ContainerEvent
3. FocusEvent
4. KeyEvent
5. MouseEvent
6. WindowEvent

The following table shows the description of various event classes:


Event classes Description Event Source
ActionEvent Generated when a button is pressed, a Button, JButton
list item is double-clicked, or a menu
item is selected.
AdjustmentEvent Generated when a scrollbar is Scrollbar, JScrollbar
manipulated
ComponentEvent Generated when a component is hidden, Component
moved, resized or becomes visible.
ContainerEvent Generated when a component is added Component
to or removed from a container
FocusEvent Generated when a component gains or Component
loses keyboard focus
ItemEvent Generated when a checkbox or list item List, JList
is clicked; also occurs when a choice Choice, Checkbox
selection is made or a checkable menu
item is selected or deselected.
KeyEvent Generated when the input is received keyboard
from the keyboard
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 36

MouseEvent Generated when the mouse is dragged, Mouse


moved, clicked, pressed or released;
also generated when the mouse enters
or exits a component.
MouseWheelEvent Generated when the mouse wheel is Mouse
moved
TextEvent Generated when the value of the text TextField or TextArea
field or text area is changed.
WindowEvent Generated when a window is activated, Window
closed, deactivated.

EVENT LISTENERS:

The task of handling an event is carried out by Event Listeners. When an event occurs,
1. An event object of the appropriate type is created.
2. This object is then passed to a Listener.
3. A listener must implement the interface that has the methods for event handling.

Source Event Class Class Methods Listener Interface Interface Methods


Button ActionEvent String ActionListener actionPerformed(ActionEvent ae)
getActionCommand( )

List, ItemEvent Object getItem( ) ItemListener itemStateChanged(ItemEvent ie)


Choice, ItemSelectable
Checkbox getItemSelectable( )

Keyboard KeyEvent char getKeyChar( ) KeyListener keyPressed(KeyEvent ke)


int getKeyCode( ) keyReleased(KeyEvent ke)
keyTyped(KeyEvent ke)

Mouse MouseEvent int getX( ) MouseListener mouseClicked(MouseEvent me)


int getY( ) mouseEntered(MouseEvent me)
mouseExited(MouseEvent me)
mousePressed(MouseEvent me)
mouseReleased(MouseEvent me)

MouseMotionListener mouseDragged(MouseEvent me)


mouseMoved(MouseEvent me)

Scrollbar AdjustmentEvent Adjustable getAdjustable() AdjustmentListener adjustmentValueChanged(AdjustmentEve


int getAdjustmentType() nt ae)
int getValue()

Component FocusEvent Boolean isTemporary() FocusListener focusGained(FocusEvent fe)


focusLost(FocusEvent fe)

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 37

TextField TextEvent -- TextListener textValueChanged(TextEvent)


and
TextArea

Window WindowEvent Window getWindow() WindowListener windowActivated(WindowEvent we)


int getOldState() windowClosed(WindowEvent we)
int getNewState() windowClosing(WindowEvent we)
windowDeactivated(WindowEvent we)
windowDeiconified(WindowEvent we)
windowIconified(WindowEvent we)
windowOpened(WindowEvent we)

Component ComponentEvent Component getComponent() ComponentListener componentHidden(ComponentEvent ce)


componentMoved(ComponentEvent ce)
componentResized(ComponentEvent ce)
componentShown(ComponentEvent ce)

Container ContainerEvent Component getChild() ContainerListener componentAdded(ContainerEvent ce)


Container getContainer() componentRemoved(ContainerEvent ce)

 Registering Event Listeners:


Steps:
1. Either create a class that implements a listener interface or extend a class that
implements a listener interface.
Example:
public class MyClass implements ActionListener {
----
}
2. Register your listener with the source.
Example:
Component.addActionListener(instanceOfMyClass)
3. Implement the user actions by overriding the methods of listener interface
Example:
public void actionPerformed(ActionEvent e)
{
---
// code that reacts to the action or event
--
}

Example: Program to toggle the background color on every click of button

import java.awt.*;
import java.awt.event.*;
/* class implementing ActionListener interface and it must
override all the methods of the listener interface */
public class ToggleButton extends Frame implements ActionListener
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 38

{
boolean flag=true;
Button b1;
ToggleButton(String s)
{
super(s);
setSize(400,400);
setVisible(true);
setLayout(new FlowLayout());
b1=new Button("change color");
add(b1);// placing the button control
b1.addActionListener(this); // b1=event source, registering event listener
}
public void actionPerformed(ActionEvent ae) // code to handle the event
{
String str=ae.getActionCommand();
if(str.equals("change color"))
{
flag=!flag;
repaint();
}
}

public void paint(Graphics g)


{
if(flag)
setBackground(Color.red);
else
setBackground(Color.yellow);
}
public static void main(String[] arg)
{
ToggleButton T=new ToggleButton("Handling Button Event");
}
}

Output:

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 39

5.13: ADAPTER CLASSES

All the listener interfaces holds only abstract methods and whenever a class implements a
Listener Interface, it has to implement all the methods defined in that interface.
For example, the WindowListener interface has seven methods. Whenever your class
implements such interface, your class have to implement all of the seven methods.
public void windowActivated(WindowEvent we) { }
public void windowClosed(WindowEvent we) { }
public void windowClosing(WindowEvent we) { }
public void windowDeactivated(WindowEvent we) { }
public void windowDeiconified(WindowEvent we) { }
public void windowIconified(WindowEvent we) { }
public void windowOpened(WindowEvent we) { }

It becomes tedious to implement all those methods which are not actually used. So JDK
defines corresponding Adapter Class for each of the AWT listener interfaces that have more
than one method.

Definition: Adapter Class


An Adapter Class is a companion class defined for all AWT interfaces that have more than
one method. Java adapter classes provide the default implementation of listener interfaces. If
we inherit the adapter class, we will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.

Adapter classes are very useful when you want to process only few of the events that are
handled by a particular event listener interface.

Commonly used Listener Interfaces with adapter classes:


Adapter classes Listener Interfaced

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 40

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

We can define a new class by extending one of the adapter classes and implement only those
events (methods) relevant to us.
Example:
For example, the user wants to handle the event generated during mouse move. To handle
mouse moving event, they must implement MouseMotionListener. Instead of writing the
definition of all the methods in the MouseMotionListener, they can use
MouseMotionAdapter class to implement only the mouseMoved() method.
package eventhandling;
import java.awt.*;
import java.awt.event.*;
public class Adaptertest extends Frame
{
int x,y;
String msg="";
Adaptertest(String s)
{
setVisible(true) ;
setSize(300,300);
addMouseMotionListener(new MyAdapter());
addWindowListener(

new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
class MyAdapter extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent me)
{
x=me.getX();
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 41

y=me.getY();
msg="Mouse moved at ("+x+","+y+")";
repaint();
}
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
public static void main(String[] args)
{
Adaptertest obj=new Adaptertest("Adapter Classes Demo");
}
}
Output:

5.14: ACTIONS
It is common to have multiple ways to activate the same command. The user can choose
certain function through a menu, a keystroke or a button on a toolbar. This is easy to achieve in
the AWT event model: link all events to the same listener.
Actions are the useful mechanism provided by the javax.swing package to encapsulate the
commands and to attach them to multiple event sources. That is, same command can be
associated with multiple event handlers.
For this purpose, javax.swing.Action interface and javax.swing.AbstractAction class are
used.

An Action is an object that encapsulates,


 A description of the command
 Parameters that are necessary to carry out the command

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 42

The Action interface has the following fields:


Constant Description
NAME Action name, used as button label
SMALL_ICON Icon for the action
SHORT_DESCRIPTION Short description about the action; could be used as
tooltip text
LONG_DESCRIPTION Long description about the action; could be used for
accessibility
ACCELERATOR_KEY Keystroke string; can be used as the accelerator for
the Action
ACTION_COMMAND_KEY InputMap key
MNEMONIC_KEY Key code; can be used as mnemonic for action
DEFAULT Unused; could be used for user property

Methods:

 void actionPerformed(ActionEvent event)


 void setEnabled(booleab b)
 boolean isEnabled()
 void putValue(String key, Object value)
 Object getValue(String key)
 void addPropertyChangeListener(PropertyChangeListener listener)
 void removePropertyChangeListener(PropertyChangeListener listener)

AbstractAction Class:
It is a companion class for Action interface. This class provides the default implementation for
the JFC Action interface. Standard behaviors like the get and set methods for Action object
properties are defined here.

Constructors:
 AbstractAction() - defines an Action object with a default description string
and icon
 AbstractAction(String name) - defines an Action object with a specified
description string and a default icon
 AbstractAction(String name, Icon icon) - defines an Action object with a
specified description string and icon
Example:
The following program build an Action object that can execute color change commands.
 Store the name of the command and the desired color.
 Store the color in the table of name/value pairs using the constructor of the class that
extends AbstractAction class.
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 43

 The actionPerformed() method carries out the color change action.

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

public class ActionTester extends JFrame {


JPanel buttonPanel;
public ActionTester()
{
final Action red=new ColorAction("Red",Color.RED);
final Action blue=new ColorAction("Blue",Color.BLUE);
final Action green=new ColorAction("Green",Color.GREEN);
JMenuBar menubar=new JMenuBar();
JMenu menu=new JMenu("Colors");
menubar.add(menu);
menu.add(new JMenuItem(red));
menu.add(new JMenuItem(blue));
menu.add(new JMenuItem(green));

buttonPanel =new JPanel();


InputMap imap=buttonPanel.
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
imap.put(KeyStroke.getKeyStroke("ctrl R"), "redPanel");
imap.put(KeyStroke.getKeyStroke("ctrl B"), "bluePanel");
imap.put(KeyStroke.getKeyStroke("ctrl G"), "greenPanel");

ActionMap amap=buttonPanel.getActionMap();
amap.put("redPanel",red);
amap.put("bluePanel",blue);
amap.put("greenPanel",green);

JButton RedButton=new JButton("RED");


JButton BlueButton=new JButton("BLUE");
JButton GreenButton=new JButton("GREEN");

RedButton.addActionListener(red);
BlueButton.addActionListener(blue);
GreenButton.addActionListener(green);

buttonPanel.add(RedButton);
buttonPanel.add(BlueButton);
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 44

buttonPanel.add(GreenButton);
setJMenuBar(menubar);

add(buttonPanel,BorderLayout.NORTH);
setSize(300,200);
setVisible(true);
}

class ColorAction extends AbstractAction


{
ColorAction(String name, Color c)
{
putValue(Action.NAME,name);
putValue(Action.SHORT_DESCRIPTION,name+" Panel");
putValue("color",c);
}
public void actionPerformed(ActionEvent ae)
{
Color c=(Color)getValue("color");
buttonPanel.setBackground(c);
}
}
public static void main(String[] args)
{
ActionTester obj=new ActionTester();
}
}

Output:

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 45

5.15: HANDLIND MOUSE, KEYBOARD AND WINDOW EVENTS

5.15.1: HANDLING MOUSE EVENTS


 Mouse events are generated when the mouse is dragged, moved, clicked, pressed or
released; also generated when the mouse enters or exits a component.
 To handle Mouse events, class must implement the MouseListener &
MouseMotionListener interface. Register mouse listener & mouse motion listener to receive
notifications about MouseEvents.

Syntax:
addMouseListener(this);
addMouseMotionListener(this);

Description:
Source: Mouse Event
Class: java.awt.event.MouseEvent
Listener Interface: java.awt.event.MouseListener
java.awt.event.MouseMotionListener
Example:
The following program demonstrates Mouse event handling. When user drag the mouse it
draws a line along the motion path.

import java.awt.*;
import java.awt.event.*;
public class MouseHandler extends Frame implements MouseListener,MouseMotionListener
{
int x1,y1,x2,y2;
String str;
MouseHandler(String s)
{
super(s);
setSize(300,300);
setVisible(true);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent me)
{
x1=x2;y1=y2;
x2=me.getX();
y2=me.getY();
Graphics g=this.getGraphics();
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 46

g.drawLine(x1,y1,x2,y2);
}

public void mouseMoved(MouseEvent me)


{
x1=x2;y1=y2;
x2=me.getX();
y2=me.getY();
str="Mouse Moving at ("+x2+","+y2+")";

repaint();
}
public void mouseClicked(MouseEvent me)
{
x2=me.getX();
y2=me.getY();
str="Mouse Clicked at ("+x2+","+y2+")";
repaint();
}
public void mouseEntered(MouseEvent me)
{
x2=200;y2=100;
str="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
x2=200;y2=100;
str="Mouse Exited";
repaint();
}
public void mousePressed(MouseEvent me)
{
x1=x2=me.getX();
x1=y2=me.getY();
}
public void mouseReleased(MouseEvent me)
{
str="Mouse Released at ("+x2+","+y2+")";
Graphics g=this.getGraphics();
g.drawString(str,x2,y2);
}
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 47

public void paint(Graphics g)


{
g.drawString(str,x2,y2);
}
public static void main(String arg[])
{
MouseHandler ob=new MouseHandler("Mouse event Demo");
}
}

Program Explanation:
In the above program, the MouseHanlder class extends Frame and implements both
MouseListener and MouseMotionListener interfaces to handle mouse events. These two
interfaces contain methods to receive and process the various types of mouse events. Here,
―me‖ is a reference to the object receiving mouse events. The Frame then implements all the
methods defined by the MouseListener and MouseMotionListener interfaces. These are the
event handlers for the various mouse events. Each method handles its event and then returns.

Output:

5.15.2: HANDLING KEYBOARD EVENTS

 Keyboard events are generated when the input is received from the keyboard
 To handle keyboard events, class must implement the KeyListener interface. Register key
listener to receive notifications about KeyEvents.

Syntax:
addKeyListener(this);

Description:
Source: KeyBoard
Event Class: java.awt.event.KeyEvent
Listener Interface: java.awt.event.KeyListener
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 48

Example:
The following program demonstrates keyboard input. When program receives keystrokes,
identifies the key and perform the corresponding actions specified by the program.

import java.awt.*;
import java.awt.event.*;
public class KeyboardHandler extends Frame implements KeyListener
{
int x=20,y=20;
String msg="";
KeyboardHandler(String s)
{
super(s);
setSize(300,300);
setVisible(true);
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
Font f=new Font("Monotype Corsiva",Font.BOLD,15);
msg+=ke.getKeyChar();
setFont(f);
}
public void keyTyped(KeyEvent ke){ }
public void keyReleased(KeyEvent ke)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,20,100);
}
public static void main(String arg[])
{
KeyboardHandler ob=new KeyboardHandler("Keyboard event Demo");
}
}

Output:

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 49

Program Explanation:
In the above program, the class extends Frame class and implements KeyListener to handle
the event generated through keyboard. When a key is pressed, a KEY_PRESSED event is
generated. This results in a call to the keyPressed() event handler. This handler gets the key
typed by the user through getKeyChar() method and collects the character in the string
variable msg. When the key is released, a KEY_RELEASED event is generated. The
keyReleased() event handler calls the repaint() method to display the message on the frame
window.
5.15.3: HANDLING WINDOW EVENTS

 Window events are generated when a window is activated closed, deactivated.


 To handle window events, class must implement the WindowListener interface.
 Register Window listener to receive notifications about WindowEvents.
Syntax:
addWindowListener(this);

Description:
Source: Window (Applet or Frame)
Event Class: java.awt.event.WindowEvent
Listener Interface: java.awt.event.WindowListener

Example:

import java.awt.*;
import java.awt.event.*;
public class WindowHandler extends Frame implements WindowListener
{
String msg="";
WindowHandler(String s)
{
setSize(500,500);
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 50

setVisible(true);
addWindowListener(this);
}
public void windowClosing(WindowEvent we)
{
System.out.println("Window Closed");
System.exit(0);
}
public void windowClosed(WindowEvent we)
{ System.out.println("Window Closed"); }

public void windowOpened(WindowEvent we)


{
System.out.println("Window Opened");
}
public void windowActivated(WindowEvent we)
{
msg="Window is activated";
repaint();
System.out.println("Window Activated");
}
public void windowDeactivated(WindowEvent we)
{
System.out.println("Window Deactivated");
}
public void windowIconified(WindowEvent we)
{
System.out.println("Window Iconified");
}
public void windowDeiconified(WindowEvent we)
{
System.out.println("Window DeIconified");
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
public static void main(String[] args)
{
WindowHandler obj=new WindowHandler("Window Event Demo");
}
}
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 51

Output:
Window Activated
Window Deactivated
Window Activated
Window Iconified
Window Deactivated
Window DeIconified
Window Activated
Window Deactivated
Window Activated
Window Closed

5.16: INTRODIUCTION TO SWING

Definition: SWING
Java Swing 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.
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

The features of Swing:


 Pluggable look-and feels
 Lightweight components
 Do not depend on native peers to render
themselves.
 Simplified graphics to paint on screen
 Similar behavior across all platforms
 Portable look and feel
 Only a few top level containers not lightweight.

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 46

 New components -- tress tables, sliders progress bars,


frames, text components.
 Tooltips -- textual popup to give additional help
 arbitrary keyboard event binding
 Debugging support

DIFFERENCE BETWEEN SWING & AWT:


S.No. Swing AWT
Swing is also called as AWT stands for Abstract
1
JFC’s (Java Foundation windows toolkit.
classes).
Swings are called light
weight component because AWT components are called
2 swing components sits on Heavyweight component.
the top of AWT
components and do the
3 Complex
work. components Primitive components
Swing components require AWT components require
4
javax.swing package. java.awt package.
5 Pluggable Look and Feel Look and Feel feature is
Swing components are not supported
made in purely java and AWT
components are
6
platform dependent.
they are platform
7 independent.
Works faster than AWT Works slow

Advantages of swing:
 Rich component types.
 Rich component features.
 Good component API and model support.
 Excellent Look And Feel support
 Standard GUI library.
 Stable and mature.

Disadvantages of swing:
 More memory consumption than AWT.
 More application startup time.
 When user interface is built manually, this often requires writing lot of code.

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 47

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager sets the layout manager for the component.
m)
public void setVisible(boolean b) sets the visibility of the component. It is by default
false.

MODEL-VIEW CONTROLLER DESIGN PATTERN

The Model-View-Controller is a classic design pattern often used by applications that


need the ability to maintain multiple views of the same data. The MVC pattern separates a
software component into three distinct pieces:
1. Model – stores the data
2. View – displays all or a portion of the data
3. Controller – handles the events that affect the model or view(s)

Model - (includes state data for each component):


 The model encompasses the state data for each component.

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 48

 There are different models for different types of components.


 Model has no user interface.
 Model data always exists independent of the component's visual representation.
 For example, model of a button component will hold information about the state of
button such as whether the button is pushed or not.

View - (to display component on screen):


 The view refers to how you see the component on the screen.
 The view manages the visual display of the state represented by the model. Thus using
view, the model can be represented graphically to the user.
 When model changes, view also gets updated.
 Example: For the button component the color, the size of the button will be decided by
the view.

Controller- (handles user Input):


 The controller manages the user interaction with the model.
 The controller decides the behavior of each component with respect to the events.
 Events come in many forms (a mouse click, a keyboard event).The controller decides
how each component will react to the event—if it reacts at all.
 Example: For the button component the reaction of events on the button press will be
decided by the controller.

Goal of MVC design pattern:


The goal of MVC design pattern is to separate the application object(model) from the way it is
represented to the user(view) from the way in which the user controls it(controller).
Because of this separation, multiple view and controllers can interface with the same model.

Working of MVC Architecture:


The MVC architecture of swing specifies how the three objects(Model, View and Controller)
interact.

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 49

Interaction between MVC components:


In MVC, each of the three elements—the model, the view, and the controller—
requires the services of another element to keep itself continually updated.
Once the model, view and controller objects are instantiated, the following
occurs:
1. The view registers a listener on the model
2. The controller is bound to the view
3. the controller is given a reference to the underlying model
Once a user interacts with the view, the following actions occur:
1. The view recognizes that a user action has occurred.
2. The view generates an event, which implicitly invokes appropriate method in the
controller.
3. The controller accesses the model, possibly updating it with respect to the user’s
action.
4. If the model has been altered, it notifies interested listeners of the view to display
the desired result on the screen.
The following diagram shows the interaction between model, view and controller
objects:

5.17: SWING COMPONENTS


Swing provides many standard GUI components such as buttons, lists, menus
and text areas, which you can combine to write GUI programs. Swing provides
containers such as windows and tool bars.
 Top-Level: Frames, Dialogs
 Intermediate-Level: panel, scroll pane, tabbed pane,..
 Other Swing components: button, labels,…
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.
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.
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 50

JTextField
The object of a JTextField class is a text component that allows the editing of a single line text.
It inherits JTextComponent class.
JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
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.
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.
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.
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.
JScrollBar
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an
implementation of a scrollbar. It inherits JComponent class.
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.
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.
Unlike JFrame, it doesn't have maximize and minimize buttons.

Component Constructor Methods


JLabel JLabel() void setText(String str)
JLabel(String text) String getText( )

JButton JLabel(String
JButton( ) text, int void setLabel(String str)
horizontalAlignment)
JButton(String str) String getLabel( )
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 51

JList JList() Object getSelectedValue( )


JList(String[] ) int getSelectedIndex( ) String[]
getSelectedItems( )

JRadioButton JRadioButton()
JRadioButton(String text)
JRadioButton(String text, boolean
selected)
JRadioButton(String text, Icon
icon, boolean selected)

JComboBox JComboBox() void addItem(String name)


JComboBox(Object items[]) void insertItemAt(Object obj, int
index)
void removeItem(Object obj)
void removeItemAt(int index)
void removeAllItems()
String getSelectedItem( )
int getSelectedIndex( )
void setEditiable(Boolean flag)

JCheckbox JCheckbox( ) boolean isSelected()


JCheckbox(String str) void setSelected(Boolean state)
JCheckbox(String str, boolean getState( )
boolean on) void setState(boolean on)
JCheckBox(String text, String getLabel( )
Icon icon) void setLabel(String str)

JTextField JTextField(int numChars) String getText( )


JTextField(String str, int numChars) void setText(String str)
void setEditable(boolean canEdit)

JTextArea JTextArea(int numLines, int numChars) Void setText(Stirng str)


JTextArea(String str, int numLines, int void append(String str)
numChars) void insert(String str, int index)

JPasswordField JPasswordField(int columns) void setEchoChar(char echo)


JPasswordField(String text) boolean echoCharIsSet()
JPasswordField(String text, int columns) char[] getPassword()
char getEchoChar()

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 52

Example: Swing Components


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.BevelBorder;
public class RegForm extends JFrame implements ActionListener, ItemListener
{
JFrame frame;
JLabel name,dob,gender,age,secret,address,aoi,qualification;
JTextField nametxt,agetxt,dobtxt;
JTextArea addr;
JPasswordField pwd;
JCheckBox chk1,chk2,chk3;
JRadioButton rb1,rb2;
JComboBox qual;
JButton ok;
JPanel p1,p2;
public RegForm()
{
frame=new JFrame("Registration Form");
Container cp=frame.getContentPane();
cp.setLayout(new GridLayout(10,2));
frame.setVisible(true);
frame.setSize(400,400);

name=new JLabel("Name:");
dob=new JLabel("Date of Birth:");
gender=new JLabel("Gender:");
age=new JLabel("Age:");
secret=new JLabel("Enter Secret Code:");
address=new JLabel("Address:");
aoi=new JLabel("Area of Interest:");
qualification=new JLabel("Qualification:");

ok=new JButton("OK");
ok.setBorder(BorderFactory.createLineBorder(Color.BLUE, 15));

nametxt=new JTextField();
dobtxt=new JTextField();
agetxt=new JTextField();
addr=new JTextArea();
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 53

pwd=new JPasswordField(10);
pwd.setEchoChar('*');

p1=new JPanel();
chk1=new JCheckBox("Sports");
chk2=new JCheckBox("Music");
chk3=new JCheckBox("Reading");
p1.add(chk1);
p1.add(chk2);
p1.add(chk3);

p2=new JPanel();
rb1=new JRadioButton("Male");
rb2=new JRadioButton("Female");
p2.add(rb1);
p2.add(rb2);

qual=new JComboBox();
qual.addItem("B.E");
qual.addItem("M.E");
qual.addItem("Ph.D");

cp.add(name); cp.add(nametxt);
cp.add(dob); cp.add(dobtxt);
cp.add(age); cp.add(agetxt);
cp.add(secret); cp.add(pwd);
cp.add(address); cp.add(addr);
cp.add(gender); cp.add(p2);
cp.add(aoi); cp.add(p1);
cp.add(qualification); cp.add(qual);
cp.add(ok);
ok.addActionListener(this);
chk1.addItemListener(this);
chk2.addItemListener(this);
chk3.addItemListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==ok)
JOptionPane.showMessageDialog(frame," Your Details are entered");
}
public void itemStateChanged(ItemEvent ie)
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 54

{
JCheckBox b1=(JCheckBox)ie.getItem();
String str="You have choosen "+b1.getText();
JOptionPane.showMessageDialog(frame,str);
}
public static void main(String[] args)
{
RegForm form=new RegForm();
}
}
Output:

5.18: LAYOUT MANAGEMENT

Definition: Layout Management


Layout Management is the process of arranging components within a window. Layout
manager automatically arranges several components within a window. Each container
object has a layout manager associated with it.
•Panel,Applet - Flow Layout
•Frame - Border Layout

Whenever a container is resized, the layout manager is used to position each of the
components within it.
General syntax for setting layout to container
void setLayout(LayouManager obj)
Panimalar Institute of Technology Department of CSE
23IT1301 – Object Oriented Programming – III Sem CSE 55

Various Layout Managers are

1. FlowLayout
2. BorderLayout
3. Grid Layout
4. GridbagLayout
5. Card Layout
6. BoxLayout

Arrange component without using layout Manager:


You can position components manually using setBounds() method defined
by Component class.
1. Disable the default manager of your container.
setLayout(null);
2. Givethe location and size of the component which is to be added in the container.
setBounds(int x, int y, int width, int height);
Example:
Button b=new Button(―click me‖);
b.setBounds(10,10,50,20);

FlowLayout
 FlowLayout arranges the components in rows from left-to-right and top-to-bottom
order based on the order in which they were added to the container.
 FlowLayout arranges components in rows, and the alignment specifies the alignment
of the rows. For example, if you create a FlowLayout that’s left aligned, the
components in each row will appear next to the left edge of the container.
 The flow layout manager lines the components horizontally until there is no more
room and then starts a new row of components.
 When the user resizes the container, the layout manager automatically reflows the
components to fill the available space.

Constructors:

 FlowLayout() - create default layout, which centers component and leaves 5


pixels spaces between each component.
 FlowLayout(int how)-specify how each line is aligned.
Valid values for how are:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 56

 FlowLayout(int how, int horz, int vert) - allow you to specify the horizontal and
vertical gaps that should appear between components, and if you use a constructor
that doesn’t accept these values, they both default to 5.

Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FlowDemo extends JFrame
{
public FlowDemo()
{
setTitle("Flow Layout Demo");
Container cp=getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.LEFT));
JButton ok=new JButton("OK");
JButton cancel=new JButton("CANCEL");
JButton reset=new JButton("RESET");
cp.add(ok);
cp.add(cancel);
cp.add(reset);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
FlowDemo f=new FlowDemo();
}
}
Output:

Panimalar Institute of Technology Department of CSE


23IT1301 – Object Oriented Programming – III Sem CSE 58

GridLayout
 The GridLayout layout manager divides the available space into a grid of cells, evenly
allocating the space among all the cells in the grid and placing one component in each cell.
 Cells are always same size.
 When you resize the window, the cells grow and shrink, but all the cells have identical
sizes.
Constructors:
 GridLayout(int rows, int cols) - construct a grid with specified rows and cols.
 GridLayout(int rows, int cols, int hspace, int vspace) - to specify the amount of
horizontal and vertical space that should appear between adjacent components.
Example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridDemo extends JFrame
{
GridDemo()
{
JButton[] button=new JButton[15];
int j=0;
setSize(400,300);
setVisible(true);
Container cp=getContentPane();
cp.setLayout(new GridLayout(5,5));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

for (int i=0;i<15; i++)


{
button[i]=new JButton(" "+i);
button[i].setBackground(Color.pink);
button[i].setFont(new Font("SanSerif", Font.BOLD,12));
cp.add(button[i]);
}
}
public static void main(String[] arg)
{
GridDemo cd=new GridDemo();
} }

Output:

Panimalar Institute of Technology Department of CSE


59

Border Layout
 Border layout divides the container into five regions - North, West, East, South and
Center.
 The five regions correspond to top, left, bottom, right and center of the container.
 Each region can have only one component.
Constructors:

 BorderLayout()
 BorderLayout(int hspace, int vspace) – leave space between components.

Border layout grows all components to fill the available space.


You can add components by specifying a constraint as follows:

BorderLayout.CENTER|NORTH|SOUTH|EAST|WEST

Example:
import java.awt.*;
import javax.swing.*;
public class BorderDemo extends JFrame
{
BorderLayout grid=new BorderLayout();
Button b1=new Button("Niorth");
Button b2=new Button("South");
Button b3=new Button("Center");
Button b4=new Button("East");
Button b5=new Button("West");
BorderDemo(String s)
{
super(s);
setLayout(grid);
add(b1,BorderLayout.NORTH);
add(b2,BorderLayout.SOUTH);
add(b3,BorderLayout.CENTER);
add(b4,BorderLayout.EAST);
add(b5,BorderLayout.WEST);
setSize(200,200);
setVisible(true);
}
public static void main(String arg[])
{

Panimalar Engineering College Department of CSE


60

BorderDemo ob=new BorderDemo("BorderLayout Demo");


}
}
Output:

GridBag Layout - Gridlayout without limitations


 In Grid bag layout, the rows and columns have variable sizes.
 It is possible to merge two adjacent cells and make a space for placing larger
components.
 To describe the layout to grid bag manager, you must follow the procedure:

1. Create an object of type GridBagLayout. No need to specify rows and column.


2. Set this GridBagLayout object to the container.
3. Create an object of type GridBagConstraints. This object will specify how
the components are laid out within the grid bag.
4. For each components, fill in the GridBagConstraints object.Finally add the
component with the constraint by using the call:
add(Component, constraint);
GridBagConstraints:

 Gridx – specify the column position of the component to be added


 Gridy - specify the row position of the component to be added
 Gridwidth- specify how many columns occupied by the component
 Gridheight - specify how many rows occupied by the component
 fill – used when the component’s display area is larger than the component’s requested
size to determine whether and how to resize the component.
 anchor – used when the component is smaller than its display area to determine where
to palce the component

Panimalar Engineering College Department of CSE


61

 weightx – used to determine how to distribute space among columns, which is


important for specifying resizing behaviour.
 weighty - used to determine how to distribute space among rows, which is important
for specifying resizing behaviour.
 ipadx – specifies the component’s internal padding within the layout, how much to add
to the minimum width of the component. Default value=0.
 ipady - specifies the component’s internal padding within the layout, how much to add
to the minimum height of the component. Default value=0.
 insets – specifies the external padding of the component – the minimum amount of
space between the component and the edges of its display are. Default is (0,0,0,0)

Example:

import java.awt.*;
import javax.swing.*;
public class GridBagDemo extends JFrame
{
GridBagLayout gb=new GridBagLayout();
GridBagConstraints gc1= new GridBagConstraints();
GridBagConstraints gc2= new GridBagConstraints();
GridBagConstraints gc3= new GridBagConstraints();
Button b1=new Button("one");
Button b2=new Button("Two");
Button b3=new Button("Three");

GridBagDemo(String s)
{
super(s);
setLayout(gb);
gc1.gridx=0;
gc1.gridy=0;
gc1.gridwidth=2;
gc1.gridheight=1;
gc2.gridx=0;
gc2.gridy=1;
gc2.gridwidth=1;
gc2.gridheight=1;
gc3.gridx=1;
gc3.gridy=1;

Panimalar Engineering College Department of CSE


62

gc3.gridwidth=1;
gc3.gridheight=1;
add(b1,gc1);
add(b2,gc2);
add(b3,gc3);
setSize(200,200);
setVisible(true);
}
public static void main(String arg[])
{
GridBagDemo ob=new GridBagDemo("GridBagLayout Demo");
}
}

Card Layout
 The card layout is unique in which it stores several different layouts.
 Each layout can be thought of as being on a separate index card in a deck that can be
shuffled so that any card is on top at a given time.
 You can prepare the other layouts and have them hidden, ready to be activated when
needed.
Constructors:
 CardLayout() - creates a default card layout.
 CardLayout(int horz, int vert) - allows to specify the horizontal and vertical
space left between components.
Example:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class CardDemo extends JFrame implements ActionListener
{
JCheckBox win98, winNT, solaris, mac;
JPanel osCards;
CardLayout cardLO;
JButton Win, Others;
CardDemo(String s)
{
super(s);

Win=new JButton("Windows");

Panimalar Engineering College Department of CSE


63

Others=new JButton("Others");
add(Win);
add(Others);

cardLO=new CardLayout();
osCards=new JPanel();
osCards.setLayout(cardLO); // set Panel layout to card layout

win98=new JCheckBox("Window 98/XP",null,true);


winNT=new JCheckBox("Windows NT/2000");
solaris=new JCheckBox("Solaris");
mac=new JCheckBox("MacOs");

JPanel winpan=new JPanel();


winpan.add(win98);
winpan.add(winNT);

JPanel otherpan=new JPanel();


otherpan.add(solaris);
otherpan.add(mac);

// add panels to card deck panel


osCards.add(winpan,"Windows");
osCards.add(otherpan,"Others");

// add cards to main window JFrame


add(osCards);
Win.addActionListener(this);
Others.addActionListener(this);

setVisible(true);
setSize(400,400);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==Win)
cardLO.show(osCards, "Windows");
else

Panimalar Engineering College Department of CSE


64

cardLO.show(osCards, "Others");
}
public static void main(String[] args)
{
CardDemo obj=new CardDemo("Card Layout Demo");
}
}
Output:

Box Layout
Box Layout is the default layout for a Box container.
The Box Layout manager allows multiple components to be laid out either vertically or
horizontally.
The components will not wrap. For example, a vertical arrangement of components will stay
vertically arranged when the frame is resized.

Constructor of BoxLayout class


BoxLayout(Container c, int axis): creates a box layout that arranges the components with
the given axis.

Panimalar Engineering College Department of CSE


65

The BoxLayout manager is designed with an axis parameter that specifies the type of layout.
This can be done in four ways:

X_AXIS – components are placed horizontally from left to right


Y_AXIS - components are placed vertically from top to bottom
LINE_AXIS – components are placed in a line, based on the container’s
ComponentOrientation property

Table: LINE_AXIS
ComponentOrientation Components
Horizontal Components are kept vertically, otherwise kept
horizontally
Horizontal; left to right Placed left to right, otherwise right to left
Vertical Orientations Laid from top to bottom

PAGE_AXIS – Components are placed the way text lines are written on a page, based on the
container’s ComponentOrientation property

Table: PAGE_AXIS
ComponentOrientation Components
Horizontal Horizontally, else vertically placed
Horizontal; left to right Placed left to right, otherwise right to left
Vertical Orientations Laid from top to bottom

Example:

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

public class BoxDemo extends JFrame


{
void boxDemo()
{
setTitle("Box Layout");
Container content=getContentPane();
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Box b1=new Box(BoxLayout.X_AXIS);

Panimalar Engineering College Department of CSE


66

// Box b2=new Box(BoxLayout.Y_AXIS);


for(int i=0;i<3;i++)
{
b1.add(new JButton("Button "+i));
// b2.add(new JButton("Button "+i));
}
content.add(b1);
// content.add(b2);
}
public static void main(String[] args)
{
BoxDemo demo=new BoxDemo();
demo.boxDemo();
}
}
Output: Horizontal Box

Vertical Box

Panimalar Engineering College Department of CSE


67

Example Program 1: ADDITION OF TWO NUMBERS


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

public class addition extends JFrame implements ActionListener {


JFrame fr;
JLabel no1;
JLabel no2;
JLabel result;
JTextField F1;
JTextField F2;
JTextField F3;
JButton calculate;
JButton clear;
JButton exit;

public addition()
{
JFrame fr=new JFrame("Addition of two mumer using swing");
fr.setSize(1000,1000);
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container c=fr.getContentPane();
c.setLayout(null);
c.setBackground(Color.pink);

no1 = new JLabel("Number 1");


no1.setBounds(50,80,100,30);
F1 = new JTextField();
F1.setBounds(170,80,100,30);

no2 = new JLabel("Number 2");


no2.setBounds(50,120,100,30);
F2 = new JTextField();
F2.setBounds(170,120,100,30);
result = new JLabel("Result");
result.setBounds(50,160,100,30);
F3 = new JTextField();

Panimalar Engineering College Department of CSE


68

F3.setBounds(170,160,100,30);

calculate=new JButton("Calculate");
calculate.setBounds(70,200,100,30);
calculate.addActionListener(this);

clear=new JButton("Clear");
clear.setBounds(200,200,100,30);
clear.addActionListener(this);

exit=new JButton("Exit");
exit.setBounds(340,200,100,30);
exit.addActionListener(this);

c.add(no1);
c.add(F1);
c.add(no2);
c.add(F2);
c.add(result);
c.add(F3);
c.add(calculate);
c.add(clear);
c.add(exit);
}

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource()==calculate)
{

if(F1.getText().equals("")||(F2.getText().equals("")) )
{
JOptionPane.showMessageDialog(fr,"Enter 2 integer numbers and click
calculate button");
}
else
{

int n1 = Integer.parseInt(F1.getText());

Panimalar Engineering College Department of CSE


69

int n2 = Integer.parseInt(F2.getText());
int no4 = n1 + n2; // 10
String s1 = String.valueOf(no4);
F3.setText(s1);
}
}
if(ae.getSource()==clear)
{
F1.setText("");
F2.setText("");
F3.setText("");
}

if(ae.getSource()==exit)
{
System.exit(0);
}
}
public static void main(String[] args) {
new addition();
}
}

Panimalar Engineering College Department of CSE


70

Example program 2: Student Registration form

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

class testing1 extends JFrame implements ActionListener


{
JTextField name_txt ;
JTextField fname_txt;

Panimalar Engineering College Department of CSE


71

JRadioButton male;
JRadioButton female;
JComboBox day;
JComboBox month;
JComboBox year;
JTextArea add_txtArea;
JTextField phone_txt;
JTextField email_txt;
JCheckBox chkbox;
JButton submit_btn;
JTextArea output_txtArea;

public testing1()
{
// Step 1 : Creating a frame using JFrame class
JFrame frame=new JFrame("Registration Form Example");
frame.setVisible(true);
frame.setSize(1000,1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Step 2 : setting background color of Frame.


Container c=frame.getContentPane();
c.setLayout(null);
c.setBackground(Color.pink);

// step 3 : creating JLabel for Heading


JLabel heading_lbl=new JLabel("Registration Form");
heading_lbl.setBounds(250,5,200,40);

// Step 4 : Creating JLabel for Name


JLabel name_lbl=new JLabel("Name : ");
name_lbl.setBounds(50,80,100,30);

// Creating JTextField for Name


name_txt=new JTextField();
name_txt.setBounds(180,80,180,30);

// Step 5 : Creating JLabel for Father's Name

Panimalar Engineering College Department of CSE


72

JLabel fname_lbl=new JLabel("Father's Name : ");


fname_lbl.setBounds(50,120,150,30);

// Creating JTextField for Father's name


fname_txt=new JTextField();
fname_txt.setBounds(180,120,180,30);

// Step 6 : Creating JLabel for Gender


JLabel gender_lbl=new JLabel("Gender : ");
gender_lbl.setBounds(50,160,100,30);

// Creating JRadioButton for the Male


male=new JRadioButton("Male");
male.setBounds(180,160,70,30);

// Creating JRadioButton for the Female


female=new JRadioButton("Female");
female.setBounds(280,160,80,30);

// Step 7 : Creating JLabel for Date of Birth


JLabel dob_lbl=new JLabel("Date of Birth : ");
dob_lbl.setBounds(50,200,100,30);

// Creating JComboBox for the day


String day_arr[]=new String[31];
for(int i=1;i<=31;i++)
day_arr[i-1]=Integer.toString(i);

day=new JComboBox(day_arr);
day.setBounds(180,200,40,30);

// Creating JComboBox for the month


String
month_arr[]={"Jan","Feb","March","April","May","June","July","Aug","Sept","Oct","No
v","Dec" };
month=new JComboBox(month_arr);
month.setBounds(230,200,60,30);

// Creating JComboBox for the year


String year_arr[]=new String[70];

Panimalar Engineering College Department of CSE


73

for(int i=1951;i<=2020;i++)
year_arr[i-1951]=Integer.toString(i);
year=new JComboBox(year_arr);
year.setBounds(300,200,60,30);

// Step 8 : Creating JLabel for the Address


JLabel add_lbl=new JLabel("Address : ");
add_lbl.setBounds(50,240,100,30);

// Creating JTextArea for the address


add_txtArea= new JTextArea();
add_txtArea.setBounds(180,240,180,100);

// Step 9 : Creating JLabel for the phone


JLabel phone_lbl=new JLabel("Phone No. : ");
phone_lbl.setBounds(50,350,100,30);

// Creating JTextField for the phone


phone_txt=new JTextField();
phone_txt.setBounds(180,350,180,30);

// Step 10 : Creating JLabel for the Email


JLabel email_lbl=new JLabel("Email : ");
email_lbl.setBounds(50,390,100,30);

// Creating JTextField for the Email


email_txt=new JTextField();
email_txt.setBounds(180,390,180,30);

// Step 11 : Creating JCheckBox for the license agreement


chkbox=new JCheckBox("I accept the terms and conditions");
chkbox.setBounds(50,430,300,30);

// Step 12 : Creating JButton for submit the details


submit_btn=new JButton("Submit");
submit_btn.setBounds(180,500,120,40);

// Step 13 : Adding ActionListener on submit button


submit_btn.addActionListener(this);

Panimalar Engineering College Department of CSE


74

// Step 14 : Creating JTextArea for output


output_txtArea=new JTextArea();
output_txtArea.setBounds(380,80,260,320);

// Step 15 : Adding label components to the container


c.add(heading_lbl);
c.add(name_lbl);
c.add(fname_lbl);
c.add(gender_lbl);
c.add(male);
c.add(female);
c.add(dob_lbl);
c.add(add_lbl);
c.add(phone_lbl);
c.add(email_lbl);

// Step 16 : Adding JTextField, JTextArea, JComboBox, JCheckBox, JRadioButton to the


container
c.add(name_txt);
c.add(fname_txt);
c.add(day);
c.add(month);
c.add(year);
c.add(add_txtArea);
c.add(phone_txt);
c.add(email_txt);
c.add(chkbox);
c.add(submit_btn);
c.add(output_txtArea);
} // ending of constructor

// step 17 :action to be performed when the button is clicked


public void actionPerformed(ActionEvent event)
{
if(chkbox.isSelected()==true)
{
String name=name_txt.getText();
String fname=fname_txt.getText();
String gender="Male";
if(female.isSelected()==true)

Panimalar Engineering College Department of CSE


75

gender="Female";
String day_name=(String)day.getSelectedItem();
String month_name=(String)month.getSelectedItem();
String year_name=(String)year.getSelectedItem();
String add=add_txtArea.getText();
String phone=phone_txt.getText();
String email=email_txt.getText();

// displaying value in the JTextArea


output_txtArea.setText(" Name : " +name + "\n Father's Name : " +fname + "\n
Gender : "+gender + "\n Date of Birth : "+day_name + " "+month_name + " "
+year_name + "\n Address : "+add + " \n Phone no : "+phone + "\n Email : "+email
+ "\n ");

}
else
{
output_txtArea.setText("Please accept the terms and condition and submit your
details");
}
}

public static void main(String args[])


{
new testing1();
}
}
Sample Output:

Panimalar Engineering College Department of CSE


76

EXAMPLE 3:
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l;
MouseListenerExample()
{
addMouseListener(this);

l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}

Panimalar Engineering College Department of CSE


77

public void mousePressed(MouseEvent e) {


l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
OUTPUT:

JLabel

The JLabel class is used to display a label i.e., static text. A JLabel object can be created
using any one of the following constructors:

JLabel(Icon icon)
JLabel(String str)

Panimalar Engineering College Department of CSE


78

JLabel(String str, Icon icon, int align)

In the above constructors icon is used to specify an image to be displayed as a label. Icon is a
predefined interface which is implemented by the ImageIconclass. str is used to specify the
text to be displayed in the label and align is used to specify the alignment of the text.

public class MyFrame extends JFrame


{
JLabel l;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
l = new JLabel("This is a label!");
add(l);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Output of the above code is as follows:

JButton
JButton class provides functionality of a button. JButton class has three constuctors,

JButton(Icon ic)

Panimalar Engineering College Department of CSE


79

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.

Example using JButton


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{

testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.
setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}

Panimalar Engineering College Department of CSE


80

JTextField
JTextField is used for taking input of single line of text. It is most widely used text
component. It has three constructors,
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
cols represent the number of columns in text field.

Example using JTextField


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTextField extends JFrame
{
public MyTextField()
{
JTextField jtf = new JTextField(20); //creating JTextField.
add(jtf); //adding JTextField to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new MyTextField();
}
}

Panimalar Engineering College Department of CSE


81

JTextArea
Unlike the text field, text area allows the user to input multiple lines of text. To create a text
area in Swing, you use JTextArea class.
The JTextArea class uses PlainDocument model, therefore, it cannot display multiple fonts.
The display area of the JTextArea is controlled by its rows and columns properties. We often
use JTextArea with scroll pane to add horizontal and vertical scrollbars.

Example of creating a text area by using JTextArea Class

In this example, we create a new text area using the JTextArea class.
Here is the screenshot of the demo application:

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

public class Main {

public static void main(String[] args) {


final JFrame frame = new JFrame("JTextArea Demo");
JTextArea ta = new JTextArea(10, 20);

JScrollPane sp = new JScrollPane(ta);

frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 220);
frame.getContentPane().add(sp);
frame.setVisible(true);
}
}

Panimalar Engineering College Department of CSE


82

JCheckBox
JCheckBox class is used to create checkboxes in frame. Following is constructor for
JCheckBox,
JCheckBox(String str)

Example using JCheckBox


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("no"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("maybe"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

Panimalar Engineering College Department of CSE


83

JRadioButton
Radio button is a group of related button in which only one can be selected. JRadioButton
class is used to create a radio button in Frames. Following is the constructor for
JRadioButton,
JRadioButton(String str)

Example using JRadioButton


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

Panimalar Engineering College Department of CSE


84

JList
A list is a widget that allows user to choose either a single selection or multiple
selections. To create a list widget you use JList class. The JList class itself does not support
scrollbar. In order to add scrollbar, you have to use JScrollPane class together with JList
class. The JScrollPane then manages a scrollbar automatically.
Here are the constructors of JList class:
JList Constructors Meaning
public JList() Creates an empty List.
public JList(ListModel listModel) Creates a list from a given model
public JList(Object[] arr) Creates a list that displays elements of a given array.
public JList(Vector<?> vector) Creates a list that displays elements of a given vector.

Example of creating a simple list using JList class

In this example, we will create a simple list that displays elements of an array. When user
clicks the button, a dialog will display selected elements in the list.
The getSelectedIndices() method is used to get selected indices and getElementAt() method is
used to get element by index.

JScrollBar
A scrollbar consists of a rectangular tab called slider or thumb located between two arrow
buttons. Two arrow buttons control the position of the slider by increasing or decreasing a
number of units, one unit by default. The area between the slider and the arrow buttons is
known as paging area. If user clicks on the paging area, the slider will move one block,
normally 10 units. The slider’s position of scrollbar can be changed by:
 Dragging the slider up and down or left and right.
 Pushing on either of two arrow buttons.
 Clicking the paging area.

Panimalar Engineering College Department of CSE


85

In addition, user can use scroll wheel on computer mouse to control the scrollbar if it is
available.
To create a scrollbar in swing, you use JScrollBar class. You can create either vertical or
horizontal scrollbar.
Here are the JScrollBar’s constructors.
Constructors Descriptions
JScrollBar() Creates a vertical scrollbar.
JScrollBar(int orientation) Creates a scrollbar with a given orientation.
JScrollBar(int orientation, int Creates a scrollbar with a given orientation and initialize
value, int extent, int min, int the following scrollbar’s properties: value, extent,
max) minimum, and maximum.

Example of using JScrollBar

In this example, we will create a vertical and horizontal scrollbars. The position of the slider
will be updated whenever the position of the slider changed.
Here is the screenshot of the demo application:

JComboBox
Combo box is a combination of text fields and drop-down list.JComboBox component is
used to create a combo box in Swing. Following is the constructor for JComboBox,
JComboBox()
JComboBox(E[] items)

Example using JComboBox


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{

Panimalar Engineering College Department of CSE


86

String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name.


public Test()
{
JComboBox jc = new JComboBox(name); //initialzing combo box with list of name.
add(jc); //adding JComboBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

A program to change background color of a frame (Using Action Event)


import java.awt.*; //importing awt package
import javax.swing.*; //importing swing package
import java.awt.event.*; //importing event package

//For an event to occur upon clicking the button, ActionListener interface should be
implemented
class StColor extends JFrame implements ActionListener{

JFrame frame;
JPanel panel;
JButton b1,b2,b3,b4,b5;

StColor(){

Panimalar Engineering College Department of CSE


87

frame = new JFrame("COLORS");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel = new JPanel(); //Creating a panel which is a container and will hold all the buttons
panel.setSize(100, 50);

b1 = new JButton("BLUE"); //Creating a button named BLUE


b1.addActionListener(this); //Registering the button with the listener

b2 = new JButton("RED"); //Creating a button named RED


b2.addActionListener(this); //Registering the button with the listener

b3 = new JButton("CYAN");//Creating a button named CYAN


b3.addActionListener(this);//Registering the button with the listener

b4 = new JButton("PINK"); //Creating a button named PINK


b4.addActionListener(this); //Registering the button with the listener

b5 = new JButton("MAGENTA"); //Creating a button named MAGENTA


b5.addActionListener(this); //Registering the button with the listener

//Adding buttons to the Panel


panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(b4);
panel.add(b5);

frame.getContentPane().add(panel); //adding panel to the frame


frame.setSize(500,300);
frame.setVisible(true);
frame.setLayout(new FlowLayout());

}
//The below method is called whenever a button is clicked
@Override
public void actionPerformed(ActionEvent e) {

//This method returns an object of the button on which the Event-

Panimalar Engineering College Department of CSE


88

//Pressing of button initially occurred


Object see = e.getSource();

if(see ==(b1)){ //Checking if the object returned is of button1


frame.getContentPane().setBackground(java.awt.Color.blue); //changing the panel color
to blue
}
if(see == b2){ //Checking if the object returned is of button2
frame.getContentPane().setBackground(java.awt.Color.red); //changing the panel
color to red
}
if(see == b3){ //Checking if the object returned is of button3
frame.getContentPane().setBackground(java.awt.Color.cyan);//changing the panel color
to cyan
}
if(see == b4){ //Checking if the object returned is of button4
frame.getContentPane().setBackground(java.awt.Color.pink); //changing the panel
color to pink
}
if(see == b5){ //Checking if the object returned is of button5
frame.getContentPane().setBackground(java.awt.Color.magenta); //changing the panel
color to magenta
}
}
}

class Test {
public static void main(String[] args) {
StColor o = new StColor();
}
}

Panimalar Engineering College Department of CSE


89

Ouput:

Java JTextArea Example with ActionListener

1. import javax.swing.*;
2. import java.awt.event.*;
3. public class TextAreaExample implements ActionListener{
4. JLabel l1,l2;
5. JTextArea area;
6. JButton b;
7. TextAreaExample() {
8. JFrame f= new JFrame();
9. l1=new JLabel();
10. l1.setBounds(50,25,100,30);
11. l2=new JLabel();
12. l2.setBounds(160,25,100,30);
13. area=new JTextArea();
14. area.setBounds(20,75,250,200);
15. b=new JButton("Count Words");
16. b.setBounds(100,300,120,30);
17. b.addActionListener(this);
18. f.add(l1);f.add(l2);f.add(area);f.add(b);
19. f.setSize(450,450);
20. f.setLayout(null);
21. f.setVisible(true);
22. }
23. public void actionPerformed(ActionEvent e){
24. String text=area.getText();
25. String words[]=text.split("\\s");
26. l1.setText("Words: "+words.length);

Panimalar Engineering College Department of CSE


90

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


28. }
29. public static void main(String[] args) {
30. new TextAreaExample();
31. }
32. }

JWindow
Window is a part of Java Swing and it can appear on any part of the users desktop. It is
different from JFrame in the respect that JWindow does not have a title bar or window
management buttons like minimize, maximize, and close, which JFrame has. JWindow can
contain several components such as buttons and labels.

Constructor of the class are:


 JWindow() : creates an empty Window without any specified owner
 JWindow(Frame o) :creates an empty Window with a specified frame as its owner
 JWindow(Frame o) : creates an empty Window with a specified frame as its owner
 JWindow(Window o) : creates an empty Window with a specified window as its owner
 JWindow(Window o, GraphicsConfiguration g) : creates an empty window with a
specified window as its owner and specified graphics Configuration.
 JWindow(GraphicsConfiguration g) :creates an empty window with a specified
Graphics Configuration g.

Example:

// java Program to create a simple JWindow


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

Panimalar Engineering College Department of CSE


91

class solveit extends JFrame implements ActionListener {


// frame
static JFrame f;
// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");

// create a object
solveit s = new solveit();

// create a panel
JPanel p = new JPanel();
JButton b = new JButton("click");

// add actionlistener to button


b.addActionListener(s);

// add button to panel


p.add(b);
f.add(p);

// set the size of frame


f.setSize(400, 400);
f.show();
}

// if button is pressed
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("click")) {
// create a window
JWindow w = new JWindow(f);

// set panel
JPanel p = new JPanel();

// create a label

Panimalar Engineering College Department of CSE


92

JLabel l = new JLabel("this is a window");

// set border
p.setBorder(BorderFactory.createLineBorder(Color.black));

p.add(l);
w.add(p);

// set background
p.setBackground(Color.red);

// setsize of window
w.setSize(200, 100);

// set visibility of window


w.setVisible(true);

// set location of window


w.setLocation(100, 100);
}
}
}

JMenu
The JMenuBar class is used to display menubar on the window or frame. It may have several
menus.

Panimalar Engineering College Department of CSE


93

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.
JMenuBar class declaration
public class JMenuBar extends JComponent implements MenuElement, Accessible
JMenu class declaration
public class JMenu extends JMenuItem implements MenuElement, Accessible
JMenuItem class declaration
public class JMenuItem extends AbstractButton implements Accessible, MenuElement

Java JMenuItem and JMenu Example:


import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}

Panimalar Engineering College Department of CSE


94

OUTPUT:

Java 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.
Unlike JFrame, it doesn't have maximize and minimize buttons.

JDialog class declaration


Let's see the declaration for javax.swing.JDialog class.
public class JDialog extends Dialog implements WindowConstants, Accessible,
RootPaneContainer

Constructor Description

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, It is used to create a dialog with the specified title, owner
boolean modal) Frame and modality.

Panimalar Engineering College Department of CSE


95

Java JDialog Example

// java Program to create a simple JDialog


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class DialogExample extends JFrame implements ActionListener {

// frame
static JFrame f;

// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");

// create a object
DialogExample s = new DialogExample();

// create a panel
JPanel p = new JPanel();
JButton b = new JButton("click");

// add actionlistener to button


b.addActionListener(s);

// add button to panel


p.add(b);
f.add(p);

// set the size of frame


f.setSize(400, 400);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("click")) {
// create a dialog Box
JDialog d = new JDialog(f, "dialog Box");

// create a label

Panimalar Engineering College Department of CSE


96

JLabel l = new JLabel("this is a dialog box");


d.add(l);

// setsize of dialog
d.setSize(100, 100);

// set visibility of dialog


d.setVisible(true);
}
}
}

OUTPUT:

Java JOptionPane

The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm
dialog box and input dialog box. These dialog boxes are used to display information or get input from
the user. The JOptionPane class inherits JComponent class.

JOptionPane class declaration


1. public class JOptionPane extends JComponent implements Accessible

Common Constructors of JOptionPane class


Constructor Description
JOptionPane() It is used to create a JOptionPane with a test message.
It is used to create an instance of JOptionPane to display a
JOptionPane(Object message)
message.
JOptionPane(Object message, int It is used to create an instance of JOptionPane to display a
messageType message with specified message type and default options.

Panimalar Engineering College Department of CSE


97

Common Methods of JOptionPane class


Methods Description
It is used to create and return a new
JDialog createDialog(String title)
parentless JDialog with the specified title.
static void showMessageDialog(Component It is used to create an information-message
parentComponent, Object message) dialog titled "Message".
static void showMessageDialog(Component
It is used to create a message dialog with
parentComponent, Object message, String title, int
given title and messageType.
messageType)
It is used to create a dialog with the options
static int showConfirmDialog(Component
Yes, No and Cancel; with the title, Select an
parentComponent, Object message)
Option.
It is used to show a question-message dialog
static String showInputDialog(Component
requesting input from the user parented to
parentComponent, Object message)
parentComponent.
It is used to set the input value that was
void setInputValue(Object newValue)
selected or input by the user.

Java JOptionPane Example: showMessageDialog()


1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }

Java JOptionPane Example: showMessageDialog()


1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();

Panimalar Engineering College Department of CSE


98

6. JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNI
NG_MESSAGE);
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }

Java JOptionPane Example: showInputDialog()


1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. String name=JOptionPane.showInputDialog(f,"Enter Name");
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }

Java JOptionPane Example: showConfirmDialog()


1. import javax.swing.*;
2. import java.awt.event.*;
3. public class OptionPaneExample extends WindowAdapter{
4. JFrame f;
5. OptionPaneExample(){
6. f=new JFrame();
7. f.addWindowListener(this);
8. f.setSize(300, 300);

Panimalar Engineering College Department of CSE


99

9. f.setLayout(null);
10. f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
11. f.setVisible(true);
12. }
13. public void windowClosing(WindowEvent e) {
14. int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
15. if(a==JOptionPane.YES_OPTION){
16. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. }
18. }
19. public static void main(String[] args) {
20. new OptionPaneExample();
21. }
22. }

Panimalar Engineering College Department of CSE

You might also like