UNIT-V Topics To Be Covered: Object Oriented Programming Through Java

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 111

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

UNIT-V topics to be covered


Advantages of GUI over CUI

The AWT class hierarchy

Introduction to swings

Swings elements- JComponent, JFrame

User interface components- Jlabels,Jbutton,JScrollbars.


Text components, check box, check box groups, choices

Lists panels- scrollpane, menubar, graphics

Layout managers- boarder, grid, flow, card and grid bag.

Event handling: Delegation event model, closing a Frame, mouse and


keyboard events
Adapter classes.

Vigneswara Reddy,IT of Dept


What is GUI?(Graphical User Interface)
It is a user interface used to interact with the application by makes
use of graphics.
- User can interact with the application using pointing devices like
mouse, touch screen.
- Ex- windows, Linux.
What is CUI?(Character User Interface)
also called command line interface(CLI)
- user can interact with the application by giving commands through
the keyboard in the form of Text.
- Ex- DOS, Unix

Vigneswara Reddy,IT of Dept


ADVANTAGES OF GUI OVER CUI
 GUI is user friendly interfaces whereas CUI is not user
friendly.
 GUI provides graphical icons to interact while the CUI
(Character User Interface) offers the simple text-based
interfaces.
 GUI makes the application more entertaining and interesting
on the other hand CUI does not.
 New user can easily interact with graphical user interface by
the visual indicators but it is difficult in Character user
interface.
 Windows concept in GUI allow the user to view, manipulate
and control the multiple applications at once while in CUI
user can control one task at a time.

Vigneswara Reddy,IT of Dept


button menus title bar menu bar combo box

scroll
bars

INTERNET EXPLORER WINDOW WITH GUI


COMPONENTS

Vigneswara Reddy,IT of Dept


AWT (ABSTRACT WINDOW TOOLKIT)

 AWT is used to create GUI components


 All these GUI components are available in the package
called java.awt.
 GUI components which are created by the awt are static
means they are not in live.
 To make the components dynamic extra interface is needed
which is called event.
 Available in the java.awt.event package

 AWT components are platform dependent means


appearance of the components are varied from operating
system to operating system.
 To make the single format Swings are to be used.

Vigneswara Reddy,IT of Dept


AWT HIERARCHY

Vigneswara Reddy,IT of Dept


 AWT components are place by creating Frame object
 It can by done in two ways

 1. by instantiating Frame class.

 2. create a class extends from Frame class

Ex1 for instantiating Frame class


import java.awt.*;
import java.awt.event.*;
public class Frame1{
public static void main(String args[])
{
Frame f= new Frame();
f.setVisible(true);
f.setSize(400,400);
f.setBackground(Color.GREEN);
f.setTitle("Hi SNIST");
}
}

Vigneswara Reddy,IT of Dept


 Example2- create a class extends from Frame class
import java.awt.*;
class Frame2 extends Frame
{
Frame2()
{
setTitle("Demo");
setSize(300,300);
setVisible(true);
setBackground(Color.GREEN);
}}
class Frame2Ex
{
public static void main(String args[])
{
new Frame2();
}
}

Vigneswara Reddy,IT of Dept


Commonly used Methods of Component class:
The methods of Component class are widely used in java swing that
are given below.

Method Description
add a component on another
public void add(Component c)
component.
public void setSize(int width,int height) sets size of the component.
sets the layout manager for the
public void setLayout(LayoutManager m)
component.
sets the visibility of the component.
public void setVisible(boolean b)
It is by default false.

Vigneswara Reddy,IT of Dept


CREATE LABEL

 Label class is used to create labels


 Label constructors
1. Label()- creates empty label
2. Label(String text) - Label with specified text
3. Label(String text, int alignment)
- creates a label with specified text and alignment( CENTER,LEFT,RIGHT)

Vigneswara Reddy,IT of Dept


import java.awt.*;
public class TestLabel
{
TestLabel()
{
Frame fm=new Frame(); //Creating a frame.
Label lb = new Label("welcome to java graphics",Label.LEFT); //Creating a label
fm.add(lb); //adding label to the frame.
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true.
}
public static void main(String args[])
{
TestLabel tl = new TestLabel();
}
}

Vigneswara Reddy,IT of Dept


CREATE A BUTTON
import java.awt.*;
import java.awt.event.*;
public class TestButton extends Frame {
public TestButton()
{
Button btn=new Button("Hello World");
add(btn); //adding a new Button.
setSize(400, 500); //setting size.
setTitle("SNIST"); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.
}
public static void main (String[] args)
{
TestButton ta = new TestButton(); //creating a frame.
}
}
Vigneswara Reddy,IT of Dept
INTRODUCTION TO SWINGS
 Java provides rich set of libraries to create GUI in platform
independent way and light weight through swings.
 Swings are built on top of the awt components.

 Swings are extension of awt package.

 Swings has several classes to provide more powerful and


flexible components than awt components.
 These classes are available in javax.swing package these
components are pure java components.
 Swings can also provide classes like Tree, TabbedPane, Slider,
ColorPicker, Table etc.

Vigneswara Reddy,IT of Dept


SWINGS HIERARCHY

Vigneswara Reddy,IT of Dept


SWINGS ELEMENTS
 Jcomponent
it is a base class for all swing GUI components which is
extended from Component and Container classes
 JFrame

- Jframe is swings version of frame and is inherited from


Frame class.
- used to place all the swings GUI components.

Vigneswara Reddy,IT of Dept


 To place all swing components JFrame is to be created
 How do you create a JFrame class.

 JFrame is created in two ways.

1. By instantiating JFrame class

2. By extending Jframe class

Vigneswara Reddy,IT of Dept


1. BY INSTANTIATING JFRAME CLASS

import javax.swing.*;
import java.awt.*;
public class SwingP1{
public static void main(String args[])
{
JFrame f= new JFrame(“Welcome to SNIST");
f.setVisible(true);
f.setSize(400,400);
}
}

Vigneswara Reddy,IT of Dept


2. BY EXTENDING JFRAME CLASS
import javax.swing.*;
import java.awt.*;
public class SwingP2 extends JFrame
{
public SwingP2()
{
setTitle(“Welcome to SNIST");
setSize(300,500);
setVisible(true);
}
public static void main(String args[])
{
new SwingP2();
}
}

Vigneswara Reddy,IT of Dept


SWING ELEMENTS

JLabel JButton JScrollbar


JTextField JPasswordField JTextArea
ImageIcon JOptionpane

Vigneswara Reddy,IT of Dept


DIFFERENCE BETWEEN AWT AND SWINGS

AWT SWINGS
AWT components platform dependent Swings components are platform
AWT components are heavy weight Light weight
Less components than Swings More components are created with
swings like tables, trees, color
picker, tabbedpane etc.

Vigneswara Reddy,IT of Dept


 Jlabel
displays text or an image or both.
constructors in JLabel class
 JLabel() creates a JLabel instance with no image and empty
string.
 Jlabel(String text) - label with specified Text

 Jlabel(String s, Icon i, int alignment);

- label with specified text, image, and alignment

Vigneswara Reddy,IT of Dept


EXAMPLE ON JLABEL

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JLabelEx extends JFrame
{
JLabelEx()
{
ImageIcon i= new ImageIcon("/example.png");
JLabel j= new JLabel("Hello",i,JLabel.CENTER);
setSize(400,400);
add(j);

setVisible(true);
}
public static void main(String args[])
{
new JLabelEx();
}
}

Vigneswara Reddy,IT of Dept


 JButton
- JButton class is used to create a push button.
- it is subclass of the AbstractButton class, which extends
Jcomponent.
o Constructors in JButton class

1. JButton(Icon i)
2. JButton(String s);
3. Jbutton(String s,Icon i);

Vigneswara Reddy,IT of Dept


EXAMPLE ON JBUTTON CLASS
import javax.swing.*;
import java.awt.*;
//import java.awt.event.*;
public class JButtonEx extends JFrame
{
JButtonEx()
{
JButton b1= new JButton("IT-F1");
JButton b2= new JButton("IT-F2");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // setting close operation
setLayout(new FlowLayout());//set the layout
setSize(800,800);
add(b1);
add(b2);
setVisible(true);
}
public static void main(String args[])
{
new JButtonEx();
}
}
Vigneswara Reddy,IT of Dept
JTEXTFIELD CLASS
 JTextField class used for taking input of single line of text
 Constructors of JTextField

1. JTextField()

2. JTextField(int col);// create with specifies no of columns

3. JTextField(String s, int col);

Vigneswara Reddy,IT of Dept


EXAMPLE ON JTEXTFIELD CLASS
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTextField extends Jframe {
public MyTextField() {
JLabel l1= new JLabel("username");
JLabel l2= new JLabel("password");
JTextField jtf = new JTextField(20); //creating JTextField.
JTextField jtf2= new JTextField(20);
add(l1);
add(jtf);
add(l2);
add(jtf2); //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(); }} Vigneswara Reddy,IT of Dept
JScrollbar
import javax.swing.*;
public class ScrollBarExample extends JApplet{
   ScrollBarExample()   {
       JFrame jf;
       jf=new JFrame("ScrollBar");
       JPanel jp=new JPanel();
       JLabel j11=new JLabel("Scrollbar:");
       JScrollBar jsv=new JScrollBar();
       JScrollBar jsh=new JScrollBar(JScrollBar.HORIZONTAL);
       jp.add(j11);
       jp.add(jsv);
       jp.add (jsh);
       jf.add (jp);
       jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
       jf.setSize(300,200);
       jf.setVisible(true);    }
       public static void main(String[] args)
        {
            ScrollBarExample japp= new ScrollBarExample();
        }
} Vigneswara Reddy,IT of Dept
TEXT COMPONENTS
 TextComponent class has two child classes.
 1. TextFiled 2. TextArea

1. TextField- it is a text component allows the user to edit a single line of text.

Constructors for TextField

TextField() Constructs a new text field.


TextField(int columns) Constructs a new empty text field with
the specified number of columns.
TextField(String text) Constructs a new text field initialized
with the specified text.
TextField(String text, int columns) Constructs a new text field initialized
with the specified text to be displayed,
and wide enough to hold the specified
number of columns.

Vigneswara Reddy,IT of Dept


 Methods in TextField
void setText(String)
String getText()
void setEchoChar(char)//To enter text that is not displayed
void setEditable(bolean)//if false, text cann’t be modified

Vigneswara Reddy,IT of Dept


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="TextFieldDemo" width=380 height=150></applet>*/
public class TextFieldDemo extends Applet implements ActionListener {
TextField name, pass;
public void init() {
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(8);
pass = new TextField(8);
pass.setEchoChar('*');
Button b= new Button("sumbit");
add(namep);
add(name);
add(passp);
add(pass);
add(b);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
b.addActionListener(this);
}

Vigneswara Reddy,IT of Dept


public void actionPerformed(ActionEvent ae) {
repaint();}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100); }}

Vigneswara Reddy,IT of Dept


 TextArea – allows user to enter multiple lines of text
Constructors
1. TextArea()

2. TextArea(int row, int col);

3. TextArea(String str)

4. TextArea(String str, int row, int col);

5. TextArea(String str, int row, int col, int scrollbar);

Scroll bars specified in following fields


SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY

Methods
6. Void append(String str); appends the string at end

7. Void insert(String str, int pos); inserts the string in specified position

8. getText()

9. setText(String str)

10. getSelectedText()

Vigneswara Reddy,IT of Dept


// Example on TextArea
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="TextAreaDemo" width=380 height=150></applet>*/

public class TextAreaDemo extends Applet


{
public void init()
{
String str="welcome";
TextArea ta= new TextArea(str,
10,30,TextArea.SCROLLBARS_BOTH);
add(ta);
}
}

Vigneswara Reddy,IT of Dept


CHECKBOX
 Checkbox consists of a small box that can either contain mark or not. There is a
label associated with check box.
 Constructors
1. Checkbox()
2. Checkbox(String str)
3. Checkbox(String str, Boolean on)// specified name and displayed as selected
item.
4. Checkbox(String str, boolean on, CheckboxGroup cb)
// check box created with specified group.
Methods
5. setLabel(String str)
6. getLabel()
7. setState(boolean on)// sets the state of the check box
8. getState() // return state of the check box

Vigneswara Reddy,IT of Dept


 Handling checkboxes
ItemEvent class- this event is generated when a checkbox or a list item is clicked or
when a checkable menu item is selected or deselected.
Methods in ItemEvent class
1. getItem()- returns the item effected by the event
2. getStateChange()- returns the type of the state change
ItemEvent is handled by ItemListener interface
- method in ItemListener interface is itemStateChanged(ItemEvent e)
 ItemEvent is register with ItemListener by using
addItemListener(ItemListener e)

Vigneswara Reddy,IT of Dept


EXAMPLE ON CHECKBOX
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
class CheckDemo extends Frame implements ItemListener{
String msg="";
Checkbox c1,c2,c3;
CheckDemo(){
setSize(400,350);
setVisible(true);
setLayout(new FlowLayout());
c1= new Checkbox("IT");
c2= new Checkbox("ECE");
c3= new Checkbox("CSE");
add(c1);
add(c2);
add(c3);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);}
public void itemStateChanged(ItemEvent e){
repaint();}
Vigneswara Reddy,IT of Dept
public void paint(Graphics g)
{
msg="State";
g.drawString(msg,50,150);
msg="IT"+c1.getState();
g.drawString(msg,50,200);
msg="ECE"+c2.getState();
g.drawString(msg,50,300);
msg="CSE"+c3.getState();
g.drawString(msg,50,400);
}
}
class CheckboxEx{
public static void main(String args[])
{
CheckDemo cd=new CheckDemo();
}
}

Vigneswara Reddy,IT of Dept


 CheckboxGroup, Choice and List
Three types of interface components are used to allow the user to
select one item from a large number of possibilities.
 Firstis a group of connected check boxes with the property that
only one can be selected at a time.( also called radio buttons ).

 Second is Choice. Creates pop up menu

 A third is a List. A List is similar to a choice, but several items will


be displayed at a time.

Vigneswara Reddy,IT of Dept


CheckboxGroup/ radio buttons
 syntax

CheckboxGroup cg= new CheckboxGroup();

Methods
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)

Vigneswara Reddy,IT of Dept


import java.awt.*;
class CheckboxGr1 extends Frame{
Checkbox c1,c2,c3;
CheckboxGr1(){
setTitle("create Checkbox group");
setSize(400,400);
setVisible(true);
setLayout(new FlowLayout());
CheckboxGroup cbg= new CheckboxGroup();
c1= new Checkbox("IT",cbg,true);
c2=new Checkbox("CSE",cbg,false);
c3=new Checkbox("ECE",cbg,false);
add(c1);
add(c2);
add(c3);}}
class CheckboxGr {
public static void main(String args[]){
CheckboxGr1 g=new CheckboxGr1();}} Vigneswara Reddy,IT of Dept
Choice
Choice is used to create a pop up list of items which the user may choose. A
Choice control is a form of menu.
Constructor
Choice()
Methods
1. void add(String name);
2. String getSelectedItem()
3. int getSelectedIndex()// first item is at index 0

4. int getItemCount()// no of items in the list


5. void selet(int index)// select the specified index item.
6. String getItem(int index)// Returns the name of the item that contain the
value of index.

Vigneswara Reddy,IT of Dept


mport java.applet.Applet;
import java.awt.event.*;
public class ChoiceEx extends Applet implements ItemListener{
String msg=" ";
Choice ch;
public void init(){
ch= new Choice();
ch.add("RED");
ch.add("Green");
ch.add("Blue");
add(ch);
ch.addItemListener(this);}
public void itemStateChanged(ItemEvent e){
repaint();}
public void paint(Graphics g){
msg=ch.getSelectedItem();
if(msg.equals("RED"))
setBackground(Color.red);
else if(msg.equals("Green"))
setBackground(Color.green);
else if(msg.equals("Blue"))
setBackground(Color.blue);
g.drawString("selected color is"+msg,50,100);
showStatus("list action performed");
}} Vigneswara Reddy,IT of Dept
 Lists
List component presents the user with scrolling list of
text items. They can be configured to that user can select
one item or multiple items.
 Constructors

1. List() /// creates a scrolling list


2. List(int rows) // Creates a new scrolling list
initialized with the specified number of visible lines.
3. List(int rows, boolean multipleMode) //
if it is true user can select multiple items.

Vigneswara Reddy,IT of Dept


 Methods in List class
 void add(String) //To add item to the end of the list
 void add(String, int index) //To add item at an specified index
 int getItemCount() //To get the count of items in the list

 String getItem(int) //To get the specified item from the list

 void remove(int) //To remove the item form the list


 String getSelectedItem() //To get selected item from the list

Vigneswara Reddy,IT of Dept


Scrollbars
 Scrollbars are components that enable a value to be selected
by sliding a box between two arrows.
 Several components have built-in scrollbar functionality,
including text areas and scrolling lists.
 The Scrollbar class is used for creating scrollbars. A scrollbar
can be horizontal or vertical.

Vigneswara Reddy,IT of Dept


constructors
- Scrollbar( )//Constructs a new vertical scroll bar.
- Scrollbar(int style)// scroll bar with specified style either vertical or horizontal
- Scrollbar(int style, int ivalue, int visible, int min, int max);
// Constructs a new scroll bar with the specified style, initial value, visible
amount, and minimum and maximum values.
Constants
 Scrollbar.VERTICAL
 Scrollbar.HORIZONTAL

Methods

getValue()
setValue(int newValue);
int getMinimum( )
int getMaximum( )

Minimum : default 0. Maximum : default 100


Default line increment is 1 Default page increment is 10.

Vigneswara Reddy,IT of Dept


import java.awt.*; import java.awt.event.*; import java.applet.*;
/*<applet code="SBDemo" width=300 height=200></applet>*/
public class SBDemo extends Applet implements AdjustmentListener, MouseMotionListener {
String msg = ""; Scrollbar vertSB, horzSB; int width = 300, height = 200;
public void init() {
vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0,height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0, width);
add(vertSB); add(horzSB);
vertSB.addAdjustmentListener(this); horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae) {
repaint();
}
public void mouseDragged(MouseEvent me) {
int x = me.getX(); int y = me.getY();
vertSB.setValue(y); horzSB.setValue(x);
repaint();
}
public void mouseMoved(MouseEvent me) {}
public void paint(Graphics g) {
msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 6, 160);
}
}
Vigneswara Reddy,IT of Dept
MenuBar , Menu and MenuItem
1. To create a menu bar, first create an instance of MenuBar class.
This class only defines the default constructor. A menu bar contains one or
more Menu objects.
Constructor: MenuBar( )
Methods: setMenuBar(menubarInstance)
menubarInstance.add(menuInstance)

2. Next, create instances of Menu class.


Constructors: Menu( )
Menu(String menuName)
Methods: menuInstance.add(menuitemInstance)

3. Add menu items using MenuItem class.


Constructors:
MenuItem( )
MenuItem(String itemName)
MenuItem(String itemName, MenuShortcut keyAccel)
Vigneswara Reddy,IT of Dept
 You can disable or enable a menu item by using the setEnabled( )
method.

 You can determine an item’s status by calling isEnabled( ).

 You can change the name of a menu item by calling setLabel( ).

 You can retrieve the current name by using getLabel( ).

Vigneswara Reddy,IT of Dept


import java.awt.*;
class MenuBarEx extends Frame{
public MenuBarEx(){
MenuBar mb= new MenuBar();// create menu bar
setMenuBar(mb);// set menu bar
Menu br= new Menu("Branch");/ create menu
MenuItem c1,c2,c3,c4;// create menu items
c1= new MenuItem("IT");
c2= new MenuItem("CSE");
c3= new MenuItem("ECE");
c4= new MenuItem("EEE");
br.add(c1); br.add(c2); br.add(c3); br.add(c4);// add items to menu
mb.add(br);// add menu to menu bar
setSize(400,400);
setVisible(true);
}
}
class MenuBarEx1{
public static void main(String args[])
{
new MenuBarEx();
}
}
Vigneswara Reddy,IT of Dept
Panel
This is simplest invisible container that holds GUI components.

It is recommended that you place the user interface components in panels and
place the panels in a frame.

You can also place panels in a panel.

FlowLayout is the default layout for panel.

Panel()
Panel(LayoutManager layout)
//PanelEx.java
import java.awt.*;
public class PanelEx extends Frame{
public PanelEx(){
setLayout(new FlowLayout());
Panel pan1 = new Panel();
pan1.setSize(200,100);
pan1.setBackground(Color.red);
pan1.setLocation(50,50);
add( pan1 );
setSize(400,400);
setVisible(true);
Button button1 = new Button("ok");
Button button2 = new Button("cancel");
pan1.add( button1 );
pan1.add( button2 );
}
public static void main(String args[]){
new PanelEx();
}
}

Vigneswara Reddy,IT of Dept


ScrollPane

 It is similar to a panel.

 It can hold only one Component.

 If size of the component held is larger than the size of the ScrollPane,
Scroll bars will be automatically generated.
 Constructors
ScrollPane()

Vigneswara Reddy,IT of Dept


import java.awt.*;
public class ScrollPaneEx extends Frame{
public ScrollPaneEx(){
ScrollPane sPane1 = new ScrollPane();
sPane1.setSize(200,100);
sPane1.setBackground(Color.red);
sPane1.setLocation(50,50);
Panel pan1 = new Panel();
TextArea text1 = new TextArea(20,50);
pan1.add( text1 );
sPane1.add( pan1 );
add( sPane1 );
setSize(500,500);
setVisible(true);
}
public static void main(String args[]){
new ScrollPaneEx();
}
}

Vigneswara Reddy,IT of Dept


GRAPHICS
 Graphics object draws pixels on the screen that represent text and other
graphical shapes such as lines, ovals, rectangles, polygons etc.

 The graphics class is an abstract class(i.e. Graphics objects can not be


instantiated.)

 A graphics context is encapsulated by the Graphics class and is obtained


in two ways:

 It is passed to an applet when one of its various methods, such as


paint( ) or update( ), is called.

 It is returned by the getGraphics() method of Component.

Vigneswara Reddy,IT of Dept


public void paint(Graphics g)
 The paint(Graphics g) method is common to all components and containers.

 It is needed if you do any drawing or painting other than just using standard
GUI components.

 Never call paint(Graphics g), call repaint( )

How does the paint(Graphics g) method get called?

 It is called automatically by Java whenever the component or


container is loaded, resized, minimized, maximized.

 You can cause the paint method to be called at any time by calling the
component’s repaint() method.

Vigneswara Reddy,IT of Dept


class myFrame extends Frame{
……..
……..
public void paint(Graphics g){
g.drawOval(x1,y1,width,height);
……
}
}

Vigneswara Reddy,IT of Dept


THE REPAINT() METHOD WILL DO TWO THINGS:

1. It calls update(Graphics g), which writes over the old drawing in background
color (thus erasing it).

2. It then calls paint(Graphics g) to do the drawing.

x
Java coordinate system ( 0,0)

(x,y)
y

Vigneswara Reddy,IT of Dept


GRAPHICS METHODS FOR DRAWING SHAPES

g.drawString (str, x, y); //Puts string at x,y

g.drawLine( x1, y1, x2, y2 //Line from x1, y1 to x2, y2

g.drawRect( x1, y1, width, height)


//Draws rectangle with upper left corner x1, y1

g.fillRect(x1, y1, width, height) //Draws a solid rectangle.

g.drawRoundRect( x, y, width, height,arcWidth, arcHeight )


//Draws rectangle with rounded corners.

g.fillRoundRect( x, y, width, height,arcWidth, arcHeight )


//Draws a solid rectangle with rounded corners.

Vigneswara Reddy,IT of Dept


(x, y)

arc height drawRoundRect


parameters

arc width height

width
(x, y)

drawOval parameters
  height
 
 

width
Vigneswara Reddy,IT of Dept
g.drawOval(x1, y1, width, height)
//Draws an oval with specified width and height. The bounding
rectangle’s top left corner is at the coordinate (x,y).The oval
touches all four sides all four sides of the bounding rectangle.

g.fillOval(x1, y1, width, height) //Draws a filled oval.

g.setColor(Color.RED)
//Sets color, it is remain active until new color is set.

Vigneswara Reddy,IT of Dept


g.drawArc(x1, y1, width, height, startAngle,arcAngle)
//Draws an arc relative to the bounding rectangle’s top-left
coordinates with the specified width and height. The arc
segment is drawn starting at startAngle and sweeps arcAngle
degrees.

90 90

180 0 180 0

270 270

Positive angle Negative angle

Vigneswara Reddy,IT of Dept


Draw Polygons
 Polygon - multisided shape
drawPolygon( xPoints[], yPoints[], points )
//Draws a polygon, with x and y points specified in arrays. Last
argument specifies number of points
//Closed polygon, even if last point different from first.
Ex

int xpoints[]={30,200,30,200,30}
int ypoints[]={30,30,200,200,30}
int x=5;
g.drawPolygon(xpoints,ypoints,x);

Vigneswara Reddy,IT of Dept


LAYOUT MANAGERS
 The LayoutManagers are used to arrange components in a particular manner in container.
These layouts can be applied for awt and swings
 Types of layout managers

1. BoarderLayout

2. CardLayout

3. GridLayout

4. FlowLayout

5. GridBagLayout

6. BoxLayout

7. GroupLayout

8. SpringLayout

the above layouts are available in the package


java.awt.*;

 To set layout manager:


myContainer.setLayout( new LayoutManger() );

Vigneswara Reddy,IT of Dept


BoarderLayout
 The BorderLayout is used to arrange the components in five regions: north,
south, east, west and center.
  Each region (area) may contain one component only
 It is the default layout of frame or window
 The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Vigneswara Reddy,IT of Dept


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

Vigneswara Reddy,IT of Dept


EXAMPLE ON BOARDERLAYOUT
import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);}
public static void main(String[] args) {
new Border();
}}
Vigneswara Reddy,IT of Dept
GridLayout
 The GridLayout is used to arrange the components in rectangular
grid. One component is displayed in each rectangle.
 Constructors

1. GridLayout(): creates a grid layout with one column per


component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with
the given rows and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns along with given
horizontal and vertical gaps.

Vigneswara Reddy,IT of Dept


import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));//creating grid layout of 3 row and 3 columns
f.setSize(300,300);
f.setVisible(true);}
public static void main(String[] args) {
new MyGridLayout();}
}
Vigneswara Reddy,IT of Dept
GridBagLayout
 Flexible lay out manager
 It aligns components by placing them within a grid of cells, allowing
components to span more than one cell.
 The rows in the grid can have different heights, and grid columns can have
different widths. 

 There are two classes that are used:


GridBagLayout: Provides the overall layout manager.
GridBagConstraints: Defines the properties of each component in
the grid such as placement, dimension and alignment

Vigneswara Reddy,IT of Dept


SPECIFYING A GRIDBAGLAYOUT
 To use a gridbag layout, you must declare the GridBagLayout and
GridBagConstaraints object and attach the layout to your applet.

Example:

GridBagLayout gridbag = new GridBagLayout();

GridBagConstraints constraints = new GridBagConstraints();

setLayout(gridbag);

Vigneswara Reddy,IT of Dept


SETTING CONSTRAINTS FOR COMPONENTS
 For each component that you add to the gridbag layout, you must first
set an instance of the GridBagContraints class.

 Let us look at an example:

constraints.gridx = 0 // put component in first cell.


constraints.gridy = 0
gridbag.setConstraints(button1, constraints);
//set the constraints to button1.
add(button1); //add to the Frame
GridBagLayout constraints
Constraints Description
gridx,gridy coordinates of the origin of the grid. Specifies position
of the component. default,
they have GrigBagConstraint.RELATIVE value which
indicates that a component can be stored to the right of
previous
gridwidth, gridheight Define how many cells will occupy component
(height and width). by The default is 1.
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.
GridBagConstraints.NONE retains the original size:
Default 
GridBagConstraints.HORIZONTAL expanded horizonta
lly 
GridBagConstraints.VERTICAL GridBagConstraints.B
OTHexpanded vertically expanded to the dimensions of
the cell

Vigneswara Reddy,IT of Dept


ipadx, ipady Specifies the component's internal padding within the
layout, how much to add to the minimum size of the
component
inserts Determines borders around the components area
anchor Used when the component is smaller than its display
area to determine where (within the display area) to
place the component. Valid values
are GridBagConstraints.CENTER (the
default),GridBagConstraints.NORTH, GridBagConstrain
ts.NORTHEAST, GridBagConstraints.EAST, GridBagC
onstraints.SOUTHEAST, GridBagConstraints.SOUTH, 
GridBagConstraints.SOUTHWEST,GridBagConstraints.
WEST, and GridBagConstraints.NORTHWEST.

weightx, weighty Specifies sizes of rows and columns

Vigneswara Reddy,IT of Dept


Vigneswara Reddy,IT of Dept
FlowLayout
 The FlowLayout is used to arrange the components in a line, one after another (in a flow).
 It is the default layout of applet or panel.
Fields of FlowLayout class:
• public static final int LEFT

• public static final int RIGHT


• public static final int CENTER

Constructors
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and
vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given
horizontal and vertical gap.

Vigneswara Reddy,IT of Dept


import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);}
public static void main(String[] args) {
new MyFlowLayout();}}

Relieving
Vigneswara Reddy,IT of Dept
CardLayout
 The CardLayout each component in a container as card. Only one component is visible at a
time.
 It treats each component as a card that is why it is known as CardLayout.
 Constructors
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.
Methods
 public void next(Container parent): is used to flip to the next card of the given container.
 public void previous(Container parent): is used to flip to the previous card of the given
container.
 public void first(Container parent): is used to flip to the first card of the given container.
 public void last(Container parent): is used to flip to the last card of the given container.
 public void show(Container parent, String name): is used to flip to the specified card
with the given name.
New Card

First Card Vigneswara Reddy,IT of Dept


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();// to add objects to the content pane layer.
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3); }

Not:- in swing Content pane layer used to hold components to retrieve content pane
getContentPane() is called so that you can add components

Vigneswara Reddy,IT of Dept


public void actionPerformed(ActionEvent e) {
card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE); }}

Vigneswara Reddy,IT of Dept


EVENT HANDLING IN JAVA

Vigneswara Reddy,IT of Dept


EVENT HANDLING
 GUI components of AWT are static in nature. To provide dynamic nature a
special interface needed is called event.
 What is an Event?

- an action is to be performed on a component to provide dynamic nature.


 How Events are generated?

- when the user interact with GUI components events are generated.
- For Example,
• Click on a Button
• Moving mouse
• Enter a character through keyboard
• Select an item from a list
• Scrolling the page.

Vigneswara Reddy,IT of Dept


TYPES OF EVENTS
 Events are two types
1. Foreground events

these events are generated when the user directly interact


with GUI components.
Ex- click a Button, moving mouse etc.
2. Background events
Events generated within the System like operating system
interrupts, time expires, hardware and software failures etc.

Vigneswara Reddy,IT of Dept


EVENT HANDLING
 Event handling is a mechanism to control or handle the events when
they are generated.
 This mechanism has a code to execute when the events are occurred is
called event handler.
 Java uses the Delegation Event Model to handle events.

 Delegation Event model has two components

1. Event source

Source is an object on which event is generated. Source object


provides the information of event occurred to event handler.
2. Event listeners
- It is known as event handler . Listeners are responsible to generate
response to an event. Listeners process the event and then return

Vigneswara Reddy,IT of Dept


THE DELEGATION EVENT MODEL
Action Events on Buttons
Event Object
ActionEvent

Event source Event listener Button ActionListener


(Event handling (actionPerformed(…))
methods)

Vigneswara Reddy,IT of Dept


 Steps involved in Event Handling
1. When user clicks a button event is generated.
2. An object of corresponding event class is created automatically
3. Event object is forwarded to registered listener interface.
4. Now the method is executed and returns.

Event classes and Listener classes are provided by package called java.awt.event

Every Event source generates an event named with Event class. Example event
generated by a Button is known as ActionEvent and event generated by
CheckBox is known as ItemEvent.

Vigneswara Reddy,IT of Dept


Event class Description Listener Interface
ActionEvent When button is pressed, textfield, menu item ActionListener
is selected and list item is double clicked
MouseEvent When mouse is dragged, moved, pressed or MouseListener
released
KeyEvent generated when input is received from KeyListener
keyboard
ItemEvent generated when check-box or list item is ItemListener
clicked
TextEvent generated when value of textarea or textfield TextListener
is changed
WindowEvent generated when window is activated, WindowListener
deactivated, deiconified, iconified, opened or
closed

ComponentEvent generated when component is hidden, ComponentEventLi


moved, resized or set visible stener

Vigneswara Reddy,IT of Dept


Event class Description Listener Interface
ContainerEvent generated when component is added or removed ContainerListener
from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

Implementation of event handling


1. Create a class which implements the Listener Interface and over ride its
methods.
2. Register a component with the Listeners.

Components are registered with Listeners by using registration methods like

 Button , MenuItem, List will use


public void addActionListener(ActionListener a){}
 CheckBox, Choice, List will use
public void addItemListener(ActionListener a){}

Vigneswara Reddy,IT of Dept


The ActionListener Interface
This interface defines the actionPerformed() method that is invoked when an
action event occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)

The AdjustmentListener Interface


void adjustmentValueChanged(AdjustmentEvent ae)

The ComponentListener Interface


This interface defines four methods that are invoked when a component is
resized, moved, shown, or hidden.
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)

The ItemListener Interface


void itemStateChanged(ItemEvent ie)

Vigneswara Reddy,IT of Dept


The ContainerListener Interface
When a component is added or removed to and from a container the following
methods are invoked.
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)

The KeyListener Interface


void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

The MouseListener Interface


void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

Vigneswara Reddy,IT of Dept


The MouseMotionListener Interface
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)

The WindowListener Interface


void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

The MouseWheelListener Interface


void mouseWheelMoved(MouseWheelEvent mwe)

The TextListener Interface


void textChanged(TextEvent te)

Vigneswara Reddy,IT of Dept


EXAMPLE ON EVENT HANDLING
public class ButtonDemo extends Frame implements ActionListener
{
  public ButtonDemo()
  {
    Button btn = new Button("OK");
    btn.addActionListener(this);
    add(btn);
  }
  public void actionPerformed(ActionEvent e)
  {
    String str = e.getActionCommand();
  }
}

Vigneswara Reddy,IT of Dept


Previous program contains a small code handle an event
1. btn Button object is created and not yet registered with Listeners.
2. the first step is implementing ActionListener to the class ButtonDemo.
3. register the button btn with the ActionListener. For this addActionListener() method of
Button class is used.  The parameter "this" refers the ActionListener.
btn.addActionListener(this);
 With the above statement, btn is linked with theActionListener.
 1. When the button btn is clicked, the button generates an event called ActionEvent. It is the
nature of the button taken care by JVM.
 2. This ActionEvent reaches the ActionListener because we registered the button with
ActionListener earlier.
 3. Now, the question is, what ActionListener does with the ActionEvent object it received?
 The ActionListener simply calls actionPerformed() method and passes the ActionEvent object
to the parameter as follows.
public void actionPerformed(ActionEvent e)
 The parameter for the above method comes from ActionListener.

 4. Finally the ActionEvent object generated by the button btn reaches the e object of


ActionEvent. All this is done by JVM implicitly. For this reason,
the getActionCommand()method of ActionEvent class knows the label of the button btn.
 String str = e.getActionCommand();
 The e represents an object of ActionEvent and the value for the e is coming from button btn.str is nothing
but the label of the button OK. Vigneswara Reddy,IT of Dept
 The whole process is put diagrammatically as follows

Vigneswara Reddy,IT of Dept


import java.awt.*;
import java.awt.event.*;
class ExOnEvent extends Frame implements ActionListener{
TextField tf;
ExOnEvent(){
tf=new TextField();
tf.setBounds(60,50,170,20); //specifies position , width and height of the GUI component
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);
add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new ExOnEvent();
}
}
Vigneswara Reddy,IT of Dept
MOUSEEVENT CLASS
 This event indicates mouse action in a component.
 This event is generated when

- a mouse is clicked
- a mouse is dragged
- a mouse is moved
- a mouse is entered
- a mouse is pressed
- a mouse is released
- a mouse is exited
This event class is available in java.awt.event.MouseEvent
package.

Vigneswara Reddy,IT of Dept


Following are fields defined in java.awt.event.MouseEvent
• MOUSE_CLICKED: the “mouse clicked” event

• MOUSE_DRAGGED : the “mouse dragged” event

• MOUSE_ENTERED: the “mouse entered” event

• MOUSE_EXITED : the “ mouse exited” event

• MOUSE_MOVED : the “moue moved” event

• MOUSE_PRESSED : the “mouse pressed “ event

• MOUSE_RELEASED: the “mouse released” event

• MOUSE_WHEEL : the “mouse wheel “ event

Vigneswara Reddy,IT of Dept


 There are two interfaces to handle mouse events
1. MouseListener Interface 2. MouseMotion Interface

The following are the methods in MouseListener interface


1. void mouseClicked(MouseEvent me)
invoked when mouse is pressed and release at same time.
2. void mouseEntered(MouseEvent me)
invoked when mouse enters a component
3. void mouseExited(MouseEvent me)
when the mouse leaves the component
4. void mousePressed(MouseEvent me)
when the mouse is pressed
5. void mouseReleased(MouseEvent me)
when the mouse is released

Vigneswara Reddy,IT of Dept


 The following are methods in MouseMotionListener interface
1. Void mouseDragged(MouseEvent me)

invoked when multiple times the mouse is dragge


2. Void mouseMoved(MouseEvent me)
invoked when the mouse is moved.

Vigneswara Reddy,IT of Dept


/*write a java program to change the background of the applet color when the mouse events are
generated*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MouseEvent1 extends Applet implements MouseListener{
public void init() {
this.addMouseListener(this);}
public void mouseClicked(MouseEvent e){
setBackground(Color.blue);
}
public void mouseEntered(MouseEvent e){
setBackground(Color.red);
}
public void mouseExited(MouseEvent e){
setBackground(Color.green);
}
public void mousePressed(MouseEvent e){
setBackground(Color.magenta);
}
public void mouseReleased(MouseEvent e){
setBackground(Color.yellow);
}
} Vigneswara Reddy,IT of Dept
 The following program changes an applet’s
background color when any mouse activity take
place. 
import java.awt.*; public void mouseClicked(MouseEvent e)
import java.applet.*; {
import java.awt.event.*; setBackground(Color.blue);
public class MouseEvent2 extends Applet }
implements public void mouseEntered(MouseEvent e)
MouseMotionListener,MouseListener{ {
setBackground(Color.cyan);
public void init() {
}
this.addMouseListener(this); public void mouseExited(MouseEvent e)
this.addMouseMotionListener(this); {
} setBackground(Color.green);
public void mouseMoved(MouseEvent event){ }
setBackground(Color.white); public void mousePressed(MouseEvent e)
{
}
setBackground(Color.magenta);
public void mouseDragged(MouseEvent event){ }
setBackground(Color.black); public void mouseReleased(MouseEvent e)
} {
setBackground(Color.yellow);
}
 
Vigneswara Reddy,IT of Dept
 Write a java to program displays the coordinates of the mouse. 
 Write a java program to draw circle using mouse coordinates.

 Write a java program to create white board.

 Write a java program to display mouse coordinates when mouse


is clicked on the applet.

Vigneswara Reddy,IT of Dept


KEYEVENT CLASS

 KeyEvent is generated when actions performed on key board.


 KeyEvent is registered with KeyListener interface to handle the
key events.
 Methods in KeyListener

1. void keyPressed(KeyEvent ke)


invoked when a key is pressed.
2. void keyReleased(KeyEvent ke)
invoked when key is released
3. void keyTyped(KeyEvent ke)
when a key is typed (pressed and released)

Vigneswara Reddy,IT of Dept


 Methods in KeyEvent class
char getKeyChar() returns the character that was entered
int getKeycode() returns the character code.

Vigneswara Reddy,IT of Dept


EXAMPLE ON KEYEVENTS

import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics.*;
import java.applet.*;
public class KeyEventEx extends Applet implements KeyListener{
String msg="";
public void init(){
addKeyListener(this);}
public void keyPressed(KeyEvent ke){
showStatus("key is pressed");}
public void keyReleased(KeyEvent ke){
showStatus("key is released");}
public void keyTyped(KeyEvent ke){
msg=msg+ke.getKeyChar();
repaint();// calls paint() explicitly and execute the updated method of component.
}
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString(msg,30,50);
}} Vigneswara Reddy,IT of Dept
ADAPTER CLASSES
 An adapter class provides empty implementation of all the methods in event
listener interfaces.
 Adapter class provides default modifications of all the methods in an interface.
 Adapter classes are useful when the user want to implement only few methods
of an interface.
 We can define a new class to act as an event listener by extending adapter
classes and implement only those events in which you are interested.
 Ex MouseMotionListener interface has two methods
mouseDragged(MouseEvent e) and mouseMoved(MouseEvent e).
but the user is interested only in mouse dragged event . If we use adapter class
(MouseMotionAdapter) We only need to implement those methods which we
are interested.

Vigneswara Reddy,IT of Dept


 Adapter classes are provided by java.awt.event package.
Some of the adapter classes are
Adapter class Listener interface

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionLister

Windowadapter WindowListener

ComponentAdapter componentListener

ContainerAdapter ContainerListener

Vigneswara Reddy,IT of Dept


 Now understand various methods in WindowListener
 It contains the following public methods:
 public void windowActivated(WindowEvent we)

      This method is used when the current Window is set to be


activated.
 public void windowClosed(WindowEvent we)

        Used when a window is closed.


 public void windowClosing(WindowEvent we)

          When a user wants to close a window this method is used.


 public void windowDeactivated(WindowEvent we)

   Used when the current window is not activated for a long time.
 public void windowDeiconfied(WindowEvent we)

          Used when a window changes its position from minimized to


normal (restored) state.
 public void windowIconified(WindowEvent we)

          Used when a window is changed from normal to minimized


state.     It makes the window visible.
Vigneswara Reddy,IT of Dept
 Create an adapter
 Create an adapter using:

 public class WindowAdapter implements WindowListner

 {

 public void windowClosed(WindowEvent e){}

 public void windowOpened(WindowEvent e){}

 public void windowIconified(WindowEvent e){}

 public void windowDeiconified(WindowEvent e){}

 public void windowActivated(WindowEvent e){}

 public void windowDeactivated(WindowEvent e){}

 public void windowClosing(WindowEvent e){}

 }  

Vigneswara Reddy,IT of Dept


In this example; we are using a close method (in other words windowClosing) of the Adapter class that shows
the benefits of using the Adapter class.
import java.awt.event.WindowAdapter;
import java.awt.Frame;
import java.awt.event.WindowEvent;
public class WindowAdapterEx extends Frame {
public WindowAdapterEx() {
WindowAdapterClose clsme = new WindowAdapterClose();
addWindowListener(clsme);
setTitle("WindowAdapter frame closing");
setSize(400, 400);
setVisible(true); }
public static void main(String args[]) {
new WindowAdapterEx(); }
}
class WindowAdapterClose extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}

Vigneswara Reddy,IT of Dept


REFERENCES

 https://www.tutorialspoint.com/swing/swing_controls.ht
m
 http://www.javatpoint.com/java-swing

 https://www.tutorialspoint.com/awt/awt_event_handling.
htm
 http://www.javatpoint.com/event-handling-in-java

 http://www.studytonight.com/java/event-handling-in-jav
a
 http://way2java.com/awt-events/java-event-handling/

 http://csis.pace.edu/~marchese/Cs396N/Lecture/L4/l4.ht
ml
 http://vip.cs.utsa.edu/classes/java/tutorial/gridbaglayout.
html

Vigneswara Reddy,IT of Dept

You might also like