Transcript Unit-2

Applet in Java
Abhishek Singh
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.
Notes :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.
Drawback of Applet
• Plugin is required at client browser to execute
applet.
Hierarchy of Applet
• As displayed in the above diagram, Applet class
extends Panel. Panel class extends Container which is
the subclass of Component.
Lifecycle of an Applet:
1.
Applet is initialized.
2.
Applet is started.
3.
Applet is painted.
4.
Applet is stopped.
5.
Applet is destroyed.
Life cycle methods for 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.
The <applet> HTML Tag
<applet
code=classfilename.class
width=applet_viewing_width_in_pixels
height=applet_viewing_height_in_pixels
[archive=archivefile]
[codebase=applet_url]
[vspace=vertical_margin]
[hspace=horizontal_margin]
[align=applet_alignment]
[alt=alternative_text]
>
<param name=param_name1
value=param_value1>
</applet>
Displaying Graphics in Applet(1)
• java.awt.Graphics class provides many methods for graphics
programming.
• Commonly used methods of Graphics class:
– public abstract void drawString(String str, int x, int y): is used
to draw the specified string.
– public void drawRect(int x, int y, int width, int height): draws
a rectangle with the specified width and height.
– 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.
– public abstract void drawOval(int x, int y, int width, int
height): is used to draw oval with the specified width and
height.
– 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.
Displaying Graphics in Applet(2)
• 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).
• public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
• public abstract void drawArc(int x, int y, int width, int
height, int startAngle, int arcAngle): is used draw a circular or
elliptical arc.
• 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.
• public abstract void setColor(Color c): is used to set the
graphics current color to the specified color.
• public abstract void setFont(Font font): is used to set the
graphics current font to the specified font.
• import java.applet.Applet; • g.drawOval(70,200,30,30);
• import java.awt.*;
•
• public class GraphicsDem •
o extends Applet{
•
• public void paint(Graphics •
g){
• g.setColor(Color.red);
•
• g.drawString("Welcome",5
0, 50);
•
• g.drawLine(20,30,20,300); •
•
• g.drawRect(70,100,30,30);
• g.fillRect(170,100,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,3
0,270);
g.fillArc(270,150,30,30,0,1
80);
}
}
•
•
•
•
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="3
00" height="300">
• </applet>
• </body>
• </html>
Java AWT
(Abstract Windowing Toolkit)
Abhishek Singh
Abstract Windowing Toolkit
• 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
• 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
height)
sets the size (width and height)
of the component.
public void
setLayout(LayoutManager m)
defines the layout manager for
the component.
public void setVisible(boolean
status)
changes the visibility of the
component, by default false.
Java AWT Example
• To create simple awt example, you need a
frame. There are two ways to create a frame
in AWT.
– By extending Frame class (inheritance)
– By creating the object of Frame class (association)
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(2)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
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();
}}
AWT UI Components
• The set of components
–
–
–
–
–
–
–
Labels
Buttons
Check Boxes (and Radio Buttons)
Text Entry Fields
Lists
Containers (to hold set of other UI elements)
Layout Managers (to control the positioning of other UI
elements within Containers)
To use a UI component, create an instance of it,
then use the “add” method to place it under the
control of a container (the basic applet window is
such a container).
Label
• A component which displays a String. Cannot be
modified by the user, but can be changed by the
application.
• Why use a label instead of an ordinary text string?
– You don’t have to redraw labels yourself using paint().
The AWT keeps track of them and redraws them when
needed.
– Labels follow the layout of the container in which they
are placed, and can be aligned with other UI
components.
Example of Label
• import java.awt.Label;
• /*<applet code=LabelTest.class
width="300" height="300">
• </applet> */
• public class LabelTest extends java.applet.Applet {
• public void init() {
• add(new Label("This is a label"));
• add(new Label("Another one“,Label.RIGHT));
• }
• }
Button
• A component which, when “clicked” with the mouse, triggers some
action.
• /*<applet code=ButtonTest.class width="300" height="300">
• </applet> */
• import java.awt.Button;
• public class ButtonTest extends java.applet.Applet {
• public void init() {
• add(new Button("Rewind"));
• add(new Button("Play"));
• add(new Button("Fast Forward"));
• add(new Button("Stop"));
• add(new Button("Eject"));
• }
• }
Check Box
• A component which can be selected or unselected (checked or
unchecked) to provide options. Unlike buttons, check boxes are not
normally used to trigger direct actions.
• import java.awt.Checkbox;
• /*<applet code=CheckboxTest.class width="300" height="300">
• </applet> */
• public class CheckboxTest extends java.applet.Applet {
• public void init() {
• add(new Checkbox("Compiler Design"));
• add(new Checkbox("Intro to Java"));
• add(new Checkbox("Java 2", true));
• add(new Checkbox("C++"));
• } }
• Note the use of the 2-argument constructor to force the “Java 2”
Checkbox to be initially checked. Method getState(), returns true or
false depending on whether the box is checked or not.
Radio Buttons
• A set of Radio Buttons is a grouped collection of Checkboxes, only one of
which may be checked at a time. A set of radio buttons is made by first
creating a CheckboxGroup object, then creating a number of Checkboxes
and associating each one with the CheckboxGroup.
• import java.awt.Checkbox;
• import java.awt.CheckboxGroup;
• /*<applet code=RadiobuttonTest.class width="300" height="300">
• </applet> */
• public class RadiobuttonTest
• extends java.applet.Applet {
• public void init() {
• CheckboxGroup cbg = new CheckboxGroup();
• add(new Checkbox("Happy", true, cbg));
• add(new Checkbox("Sad", false, cbg));
• }
• }
• Note that Radio Buttons (exclusive choice) typically
appear Round, whereas Check Boxes (nonexclusive
choice) typically appear Square.
• Method getState() can be used to check the state
of an individual radio button just as it can be used
to interrogate a check box. Method
getSelectedCheckbox() (defined in CheckboxGroup) can be used to find which radio button in a
group is selected.
• Checkbox selected;
• selected = cbg.getSelectedCheckbox();
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Text Field
A component which allows a single line of text to be edited by the user.
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.*;
public class TextFieldTest extends java.applet.Applet implements ActionListener {
public void init() {
TextField tf = new TextField(20);
tf.setEchoChar('?');
tf.addActionListener(this);
add(new Label("Password: ", Label.RIGHT));
add(tf);
}
public void actionPerformed(
ActionEvent e) {
String text = e.getActionCommand();
System.out.println(text);
}
}
• The text field generates an ActionEvent when the return
key is pressed. The “action command” contains the text in
the field at the time when the return key was pressed.
• The setEchoChar('?') method is used to change the echo
character to ‘?’. This is useful for fields which are private
(e.g., passwords). Note that if this method is not called,
the text field will echo the character typed.
• To respond to changes in the text field implement a
• “Text Listener”. This means that you have to create a class
object implementing the TextListener interface (i.e., a
method called “textValueChanged”, and add this as a text
listener to the TextField object.
• In the listener method, retrieve the current text like so:
– TextField tf = (TextField) e.getSource();
– String text = tf.getText();
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.*;
public class TextFieldTest2 extends java.applet.Applet implements ActionListener,
TextListener {
public void init() {
TextField tf = new TextField(20);
tf.addActionListener(this);
tf.addTextListener(this);
add(new Label("Name: ", Label.RIGHT));
add(tf);
}
public void actionPerformed( ActionEvent e) {
String text = e.getActionCommand();
System.out.println("Action Event: “ + text);
}
public void textValueChanged( TextEvent e) {
TextField tf = (TextField) e.getSource();
String text = tf.getText();
System.out.println("Text Event: " + text);
}
}
Choice Menu (List)
• A component which allows the user to select one option
from a number presented in a menu format.
• import java.awt.Choice;
• public class ChoiceMenuTest
• extends java.applet.Applet {
• public void init() {
• Choice c = new Choice();
• c.add("Apples");
• c.add("Ornages");
• c.add("Lemons");
• c.add("Bananas");
• add(c);
• }
• }
Event and Listener (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
MouseWheelEvent
MouseWheelListener
KeyEvent
KeyListener
ItemEvent
ItemListener
TextEvent
TextListener
AdjustmentEvent
AdjustmentListener
WindowEvent
WindowListener
ComponentEvent
ComponentListener
ContainerEvent
ContainerListener
FocusEvent
FocusListener
Steps to perform EventHandling:
• Following steps are required to perform event
handling :
– Implement the Listener interface and overrides its
methods
– Register the component with the Listener
•
For registering the component with the Listener, many classes provide the
registration methods. For example:
• Button
public void addActionListener(ActionListener a){}
• MenuItem
public void addActionListener(ActionListener a){}
• TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
• TextArea
public void addTextListener(TextListener a){}
• Checkbox
public void addItemListener(ItemListener a){}
• Choice
public void addItemListener(ItemListener a){}
• List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
EventHandling Codes:
• We can put the event handling code into one
of the following places:
– Same class
– Other class
– Annonymous class
• import java.awt.*;
• import java.awt.event.*;
• class AEvent extends Frame i
mplements 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();
}
}
Example of event handling by Outer
class(1)
• import java.awt.*;
•
• import java.awt.event.*;
•
• class AEvent2 extends Frame i •
mplements ActionListener{ •
• TextField tf;
• AEvent2(){
•
• tf=new TextField();
•
• tf.setBounds(60,50,170,20); •
• Button b=new Button("click m
e");
•
• 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 AEvent2();
}
}
Example of event handling by Outer
class(2)
•
•
•
•
•
•
•
•
•
•
•
•
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");
}
}
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 Action
Listener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String ar
gs[]){
new AEvent3();
}
}
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
import java.awt.*;
•
import java.applet.*;
•
import java.awt.event.*;
•
/*
•
<applet CODE=AdapDemo.class WIDTH=300
•
HEIGHT=200>
•
</applet>
•
*/
public class AdapDemo extends Applet
•
{
•
public String myMessage = "x = ?, y = ?"; •
public void init()
•
{
// tell the applet to listen for mouse related events •
•
addMouseListener(new MAdapter (this));
}
public void paint(Graphics g)
{
System.out.println("paint called");
g.drawString(myMessage, 50, 50);
}
}
class MAdapter extends MouseAdapter
{
me)
AdapDemo ad;
MAdapter(AdapDemo ad)
{
this.ad=ad;
}
// Respond to a mouse press on applet
public void mousePressed(MouseEvent
{
// display the x and y coordinate of mouse pointer
ad.myMessage = "x = " + me.getX() + ", y = " +
me.getY();
ad.repaint();
}
}
KeyboardListener
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
import java.awt.*;
import java.awt.event.*;
public class KeyboardListener extends Frame
implements KeyListener
{
TextField myText;
Label myLabel;
public KeyboardListener(String s )
{
super(s);
Panel myPanel =new Panel();
myLabel = new Label ("Key Listener!" ) ;
myPanel.add(myLabel);
add(myPanel);
addKeyListener ( this );
setSize ( 200,200 );
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
;
}
public void keyTyped ( KeyEvent ke )
{
myLabel.setText("Key Typed");
char youTyped= ke.getKeyChar();
myLabel.setText("You press: " + youTyped );
}
public void keyPressed ( KeyEvent ke)
{
myLabel.setText ( "Key Pressed" ) ;
}
public void keyReleased ( KeyEvent ke )
{
myLabel.setText( "Key Released" ) ;
}
public static void main (String[]args )
{
new KeyboardListener( "KeyListener Tester" )
}
}
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MouseListenerDemo
import java.awt.*;
•
import java.applet.*;
•
import java.awt.event.*;
•
/*<applet CODE=MouseListenerDemo.class
•
WIDTH=300 HEIGHT=200> </applet> */
public class MouseListenerDemo extends Applet
•
implements MouseListener
•
{
•
public String myMessage = "x = ?, y = ?";
•
public void init()
•
{
•
// tell the applet to listen for mouse related events •
addMouseListener(this);
repaint();
•
}
•
public void paint(Graphics g)
•
{
•
System.out.println("paint called");
•
g.drawString(myMessage, 50, 50);
•
}
•
// Respond to a mouse press on applet
•
public void mousePressed(MouseEvent me)
•
{
•
// display the x and y coordinate of mouse pointer
myMessage = "x = " + me.getX() + ", y = " + me.getY();
System.out.println("mouse button pressed");
repaint();
}
// you must implement all the methods of
MouseListener interface.
public void mouseClicked(MouseEvent e)
{
System.out.println("mouse button clicked");
}
public void mouseEntered(MouseEvent e)
{
System.out.println("mouse enter in application
area");
}
public void mouseExited(MouseEvent e)
{
System.out.println("mouse exit in application area");
}
public void mouseReleased(MouseEvent e)
{
System.out.println("mouse button released");
}
}
MyActionListener
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
import javax.swing.*;
•
import java.awt.Button;
•
import java.awt.FlowLayout;
•
import java.awt.TextField;
•
import java.awt.event.*;
•
public class MyActionListener extends JFrame implements •
WindowListener,
•
ActionListener
•
{
•
TextField text = new TextField(20);
•
Button b1;
•
private int numOfClicks = 0;
•
public static void main(String[] args)
•
{
•
MyActionListener myWindow = new
•
MyActionListener("Using ActonListener");
•
myWindow.setSize(350,200);
•
myWindow.setVisible(true);
}
public MyActionListener(String title)
{
super(title);
setLayout(new FlowLayout());
addWindowListener(this);
b1 = new Button("Click me");
add(b1);
add(text);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
numOfClicks++;
text.setText("Button Clicked " + numOfClicks + " times");
}
public void windowClosing(WindowEvent we)
{
dispose();
System.exit(0);
}
public void windowOpened(WindowEvent we) {}
public void windowActivated(WindowEvent we) {}
public void windowIconified(WindowEvent we) {}
public void windowDeiconified(WindowEvent we) {}
public void windowDeactivated(WindowEvent we) {}
public void windowClosed(WindowEvent we) {}
}