23IT1301 - OOPs - Unit - 5
23IT1301 - OOPs - Unit - 5
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)
{
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.
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
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.
T show()
{
return obj;
}
void disp()
{
System.out.println(obj.getClass().getName());
}
}
Output:
java.lang.String
value : java programming with Generics
java.lang.Integer
value :550
In Generic parameterized types, we can pass more than 1 data type as parameter. It works the
same as with one parameter Generic type.
}
void disp()
{
System.out.println(obj1.getClass().getName());
System.out.println(obj2.getClass().getName());
}
}
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
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.
Example:
class Main {
public static void main(String[] args) {
class DemoClass {
Example: (To iterate through the list and display the element using generic method)
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
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.
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());
Output:
F:\>java GenBounds
Average of Integer Numbers : 3.0
Average of Double Numbers : 3.3
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
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.
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.
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.
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.
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)
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");
}
}
import java.awt.*;
public class Demo{
public static void main(String arg[])
{
Frame f=new Frame("Demo");
f.setSize(600,400);
f.setVisible(true);
}
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); } }
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);
}
}
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.*;
Output:
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);
}
}
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);
}
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:
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);
}
}
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;
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)
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:
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.
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)
import java.awt.*;
import java.awt.geom.*;
public class Test_TwoDShapes extends Frame
{
Test_TwoDShapes(String s)
{
super(s);
setBounds(200,200,800,800);
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");
}
}
Output:
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
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:
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.
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");
}
}
Output:
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.
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism has the code which is known as event handler that is executed
when an event occurs.
The 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.
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
The package java.awt.event defines several types of events that are generated by various user
interface elements.
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).
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:
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
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.
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();
}
}
Output:
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.
Adapter classes are very useful when you want to process only few of the events that are
handled by a particular event listener interface.
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.
Methods:
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
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
ActionMap amap=buttonPanel.getActionMap();
amap.put("redPanel",red);
amap.put("bluePanel",blue);
amap.put("greenPanel",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);
}
Output:
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);
}
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
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:
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:
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
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"); }
Output:
Window Activated
Window Deactivated
Window Activated
Window Iconified
Window Deactivated
Window DeIconified
Window Activated
Window Deactivated
Window Activated
Window Closed
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.
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.
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.
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
JRadioButton JRadioButton()
JRadioButton(String text)
JRadioButton(String text, boolean
selected)
JRadioButton(String text, Icon
icon, boolean selected)
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:
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
1. FlowLayout
2. BorderLayout
3. Grid Layout
4. GridbagLayout
5. Card Layout
6. BoxLayout
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(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:
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);
Output:
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.
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[])
{
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;
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");
Others=new JButton("Others");
add(Win);
add(Others);
cardLO=new CardLayout();
osCards=new JPanel();
osCards.setLayout(cardLO); // set Panel layout to card layout
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
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.
The BoxLayout manager is designed with an axis parameter that specifies the type of layout.
This can be done in four ways:
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.*;
Vertical Box
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);
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);
}
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());
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();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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);
day=new JComboBox(day_arr);
day.setBounds(180,200,40,30);
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);
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();
}
else
{
output_txtArea.setText("Please accept the terms and condition and submit your
details");
}
}
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");
}
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)
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.
JButton
JButton class provides functionality of a button. JButton class has three constuctors,
JButton(Icon ic)
JButton(String str)
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();
}
}
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.
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.
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.*;
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 220);
frame.getContentPane().add(sp);
frame.setVisible(true);
}
}
JCheckBox
JCheckBox class is used to create checkboxes in frame. Following is constructor for
JCheckBox,
JCheckBox(String str)
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)
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.
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.
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.
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)
//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(){
panel = new JPanel(); //Creating a panel which is a container and will hold all the buttons
panel.setSize(100, 50);
}
//The below method is called whenever a button is clicked
@Override
public void actionPerformed(ActionEvent e) {
class Test {
public static void main(String[] args) {
StColor o = new StColor();
}
}
Ouput:
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);
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.
Example:
// create a object
solveit s = new solveit();
// create a panel
JPanel p = new JPanel();
JButton b = new JButton("click");
// 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
// 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);
JMenu
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.
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
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.
Constructor Description
JDialog(Frame owner, String title, It is used to create a dialog with the specified title, owner
boolean modal) Frame and modality.
// 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");
// create a label
// setsize of dialog
d.setSize(100, 100);
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.
6. JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNI
NG_MESSAGE);
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }
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. }