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

Java Awt and Event and Applet

Java AWT (Abstract Windowing Toolkit) is an API that provides components to build graphical user interfaces in Java applications. It uses platform-dependent components that rely on the operating system's resources. The java.awt package contains classes for common GUI components like buttons, text fields, and checkboxes. Event handling in AWT applications involves implementing listener interfaces and registering components with their corresponding listeners. Java applets allow embedding interactive programs in webpages and have a lifecycle of initialization, start, paint, stop, and destruction.

Uploaded by

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

Java Awt and Event and Applet

Java AWT (Abstract Windowing Toolkit) is an API that provides components to build graphical user interfaces in Java applications. It uses platform-dependent components that rely on the operating system's resources. The java.awt package contains classes for common GUI components like buttons, text fields, and checkboxes. Event handling in AWT applications involves implementing listener interfaces and registering components with their corresponding listeners. Java applets allow embedding interactive programs in webpages and have a lifecycle of initialization, start, paint, stop, and destruction.

Uploaded by

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

Java AWT Tutorial

Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-


based application 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 uses the resources of system.

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

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.


Container

The Container is a component in AWT that can contain another components


like buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.

Window

The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window.

Panel

The Panel is the container that doesn't contain title bar and menu bars. It can
have other components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It
can have other components like button, textfield etc.

Useful Methods of Component class

Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int sets the size (width and height) of the
height) component.
public void defines the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean changes the visibility of the component,
status) by default false.
Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a
frame in AWT.

 By extending Frame class (inheritance)


 By creating the object of Frame class (association)

Simple example of AWT by inheritance

import java.awt.*;  

class First extends Frame

{  

First()

{  

Button b=new Button("click me");  

b.setBounds(30,100,80,30);// setting button position 

add(b);//adding button into frame  

setSize(300,300);//frame size 300 width and 300 height  

setLayout(null);//no layout manager  

setVisible(true);//now frame will be visible, by default not visible  

}  

public static void main(String args[])

{  

First f=new First();  

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

Simple example of AWT by association

import java.awt.*;  

class First2

{  

First2()

{  

Frame f=new Frame();  

Button b=new Button("click me");  

b.setBounds(30,50,80,30);  

f.add(b);  

f.setSize(300,300);  

f.setLayout(null);  

f.setVisible(true);  

}  

public static void main(String args[])

{  

First2 f=new First2();  

}  
Event and Listener (Java Event
Handling)
Changing the state of an object is known as an event. For example, click on
button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.

Event classes and Listener interfaces:

Event Classes Listener Interfaces


ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEven MouseWheelListener
t
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Implement the Listener interface and overrides its methods


2. Register the component with the Listener

For registering the component with the Listener, many classes provide the
registration methods. For example:

 Button
o public void addActionListener(ActionListener a){}
 MenuItem
o public void addActionListener(ActionListener a){}
 TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
 TextArea
o public void addTextListener(TextListener a){}
 Checkbox
o public void addItemListener(ItemListener a){}
 Choice
o public void addItemListener(ItemListener a){}
 List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

EventHandling Codes:

We can put the event handling code into one of the following
places:

1. Same class
2. Other class
3. Annonymous class

Example of event handling within class:

import java.awt.*;  

import java.awt.event.*;  

class AEvent extends Frame implements ActionListener

{  

TextField tf;  

AEvent()

{  

tf=new TextField();  

tf.setBounds(60,50,170,20);  
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 AEvent();  

}  

}  
2) Example of event handling by Outer class:

import java.awt.*;  

import java.awt.event.*;  

class AEvent2 extends Frame

{  

TextField tf;  

AEvent2()

tf=new TextField();  

tf.setBounds(60,50,170,20);  

Button b=new Button("click me");  

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

Outer o=new Outer(this);  

b.addActionListener(o);//passing outer class instance  

add(b);

add(tf);  

setSize(300,300);  

setLayout(null);  

setVisible(true);  

}  

public static void main(String args[])

{  
new AEvent2();  

}  

}  

import java.awt.event.*;  

class Outer implements ActionListener

{  

AEvent2 obj;  

Outer(AEvent2 obj){  

this.obj=obj;  

}  

public void actionPerformed(ActionEvent e)

{  

obj.tf.setText("welcome");  

}  

}  

3) Example of event handling by Annonymous class:

import java.awt.*;  

import java.awt.event.*;  

class AEvent3 extends Frame

{  

TextField tf;  

AEvent3()
{  

tf=new TextField();  

tf.setBounds(60,50,170,20);  

Button b=new Button("click me");  

b.setBounds(50,120,80,30);  

b.addActionListener(new ActionListener()

{  

public void actionPerformed()

{  

tf.setText("hello");  

}  

});  

add(b);

add(tf);  

setSize(300,300);  

setLayout(null);  

setVisible(true);  

}  

public static void main(String args[])

{  

new AEvent3();  

}  

}  
Java Applet
Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at client
side.

Advantage of Applet

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

 It works at client side so less response time.


 Secured
 It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.

Drawback of Applet

 Plugin is required at client browser to execute applet.

Hierarchy of Applet
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class


provides 1 life cycle methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4


life cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only
once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides


Graphics class object that can be used for drawing oval, rectangle, arc etc.
How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html
file.

import java.applet.Applet;  

import java.awt.Graphics;  

public class First extends Applet

{  

public void paint(Graphics g)

{  

g.drawString("welcome",150,150);  

}    

}  

<html>  

<body>  

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

</applet>  

</body>  

</html>  
Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains


applet tag in comment and compile it. After that run it by: appletviewer
First.java. Now Html file is not required but it is for testing purpose only.

import java.applet.Applet;  

import java.awt.Graphics;  

public class First extends Applet{  

  

public void paint(Graphics g){  

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

}   

}  

/* 

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

</applet> 

*/  

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:

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

Example of Graphics in applet:

import java.applet.Applet;  

import java.awt.*;  

public class GraphicsDemo extends Applet

{  

public void paint(Graphics g)

{  

g.setColor(Color.red);  
g.drawString("Welcome",50, 50);  

g.drawLine(20,30,20,300);  

g.drawRect(70,100,30,30);  

g.fillRect(170,100,30,30);  

g.drawOval(70,200,30,30);  

g.setColor(Color.pink);  

g.fillOval(170,200,30,30);  

g.drawArc(90,150,30,30,30,270);  

g.fillArc(270,150,30,30,0,180);    

}  

}  

<html>  

<body>  

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

</applet>  

</body>  

</html>  
Displaying Image in Applet
Applet is mostly used in games and animation. For this purpose image is
required to be displayed. The java.awt.Graphics class provide a method
drawImage() to display the image.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object
of Image. Syntax:

1. public Image getImage(URL u, String image){}  

Other required methods of Applet class to display image:


1. public URL getDocumentBase(): is used to return the URL of the document
in which applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.

Example of displaying image in applet:

import java.awt.*;  

import java.applet.*;  

public class DisplayImage extends Applet

 { 

  Image picture;  

  public void init() 

{  

    picture = getImage(getDocumentBase(),"sonoo.jpg");  
  }  

  public void paint(Graphics g) 

{  

    g.drawImage(picture, 30,30, this);  

  }    

  }  

<html>  

<body>  

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

</applet>  

</body>  

</html>  
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to
be moved.

Example of animation in applet:

import java.awt.*;  

import java.applet.*;  

public class AnimationExample extends Applet

 {  

  Image picture;  

  public void init() 

{  

  picture =getImage(getDocumentBase(),"bike_1.gif");  

  }  

  public void paint(Graphics g)

 {  

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

{  

   g.drawImage(picture, i,30, this);  

      try{Thread.sleep(100);}catch(Exception e){}  

    }  

  }  

}  
<html>  

<body>  

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

</applet>  

</body>  

</html>  
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's
see the simple example of event handling in applet that prints a message by click on
the button.

Example of EventHandling in applet:

import java.applet.*;  

import java.awt.*;  

import java.awt.event.*;  

public class EventApplet extends Applet implements ActionListener

{  

Button b;  

TextField tf;  

public void init()

{  

tf=new TextField();  

tf.setBounds(30,40,150,20);  

b=new Button("Click");  

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

add(b);

add(tf);  

b.addActionListener(this);  

setLayout(null);  
}  

  

 public void actionPerformed(ActionEvent e)

{  

  tf.setText("Welcome");  

 }   

}  

<html>  

<body>  

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

</applet>  

</body>  

</html>  
JApplet class in Applet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.

Example of EventHandling in JApplet:

import java.applet.*;  

import javax.swing.*;  

import java.awt.event.*;  

public class EventJApplet extends JApplet implements ActionListener

{  

JButton b;  

JTextField tf;  

public void init()

{  

tf=new JTextField();  

tf.setBounds(30,40,150,20);  

b=new JButton("Click");  

b.setBounds(80,150,70,40);  

add(b);

add(tf);  

b.addActionListener(this);  

setLayout(null);  

}  
  

public void actionPerformed(ActionEvent e)

{  

tf.setText("Welcome");  

}  

}  

<html>  

<body>  

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

</applet>  

</body>  

</html>  

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

Example of Painting in Applet:

import java.awt.*;  

import java.awt.event.*;  

import java.applet.*;  

public class MouseDrag extends Applet implements MouseMotionListener

{  

public void init()

{  
addMouseMotionListener(this);  

setBackground(Color.red);  

}  

public void mouseDragged(MouseEvent me)

{  

Graphics g=getGraphics();  

g.setColor(Color.white);  

g.fillOval(me.getX(),me.getY(),5,5);  

}  

public void mouseMoved(MouseEvent me){}  

}  

<html>  

<body>  

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

</applet>  

</body>  

</html>  
Parameter in Applet
We can get any information from the HTML file as a parameter. For this
purpose, Applet class provides a method named getParameter(). Syntax:

public String getParameter(String parameterName)  

Example of using parameter in Applet:

import java.applet.Applet;  

import java.awt.Graphics;  

public class UseParam extends Applet

{  

public void paint(Graphics g)

{  

String str=getParameter("msg");  

g.drawString(str,50, 50);  

}  

}  

<html>  

<body>  

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

<param name="msg" value="Welcome to applet">  

</applet>  

</body>  

</html>  

You might also like