Sunteți pe pagina 1din 34

Java Programming

JAVA APPLET
Contents
Chapter - 9 Applet Fundamentals

Java Components

Working with Graphics

Working with Colors

Working with Fonts

Event Handling in Java

LayOut Manager

Chapter - 10 AWT Applications

Frames and Panels

Page - 1

Java Programming

Chapter - 9

APPLET Fundamentals

Objectives :
At the end of this chapter

You will understand the concepts of Applets

Java Components

Working with Graphics

Working with Colors

Working with Fonts

Event Handling in Java

Applets are small program, accessed on the internet server, transported over the internet
automatically installed and run at client browser.
Applet do not require main() method
Applet run under appletviewer or Browser
Applet class must be declared public as it will be accessed by other classes
Applet class begin with two import statements.
import java.awt.*

import java.applet.*

applet interacts with users through AWT, not through console


based I/O.
AWT package contains support for window based graphical
interface.
applet package contents class Applet
Every applet we create must be subclass of Applet class

Page - 2

Java Programming

Applet initialization and Termination


When an applet begins, the AWT calls following methods in sequence

init

Stop

paint

When applet terminates following sequence of methods calls take place :

init()
start()
paint()

Stop

Destroy

is the first method to be called Here we initialise variables. This method


is called only once during run time of applet
Called after init. Also called to restart applet after it has been stopped
Called each time HTML document is displayed on screen
paint() is the method of AWT package.
it is called each time
when applet redisplay its output.
When applet begins execution
applet window is minimized and restored
It has one parameter of type Graphics having methods like drawString(),
drawImage()

stop()
destroy()

Called when web browser leaves HTML document.


Called to suspend threads that dont need to run when the applet is not
visible.
Called when the environment determines that the applet needs to be
removed completely from memory.
Stop() method is always called before destroy() method.

Examples
import java.awt.*;
import java.applet.Applet;
/*
<applet code="HelloWorld" width=200
height=200> </applet>
*/
public class HelloWorld extends Applet
{
String msg;
public void init()
{
msg="in init : ";
}
public void start()
{
msg=msg+"in start : ";
}

public void stop()


{
msg=msg+"in stop : ";
}
public void destroy()
{
msg=msg+"in destroy : ";
}
public void paint(Graphics g)
{
msg=msg+"in paint : ";
g.drawString(msg, 50, 50);
}
}

Page - 3

Java Programming

Java Components

Visual components
Container components
Menu components

Common methods
getSize() returns height and width
getForground()
get Background()
setFont()
setEnabled(boolean b)
setSize(int width, int height)
setBounds(int x, int y, int width, int height)
setVisible(boolean b)
Visual components

Button

FileDialog

ScrollBar

Canvas

Label

TextArea

Checkbox

List

TextField

Choice

ScrollPane

Page - 4

Java Programming

Label
A Label is a displayed Label object. It is usually used to help indicate what other parts of the
GUI do, such as the purpose of a neighboring text field.
Methods :
GetText()
SetText(String s)
GetAligned()
SetAligned(int al)
Public final static int CENTER / LEFT / RIGHT
Button
A Button has a single line label and may be "pushed" with a mouse click.
Constructor public Button()
public Button(String label)
Methods
GetLabel()
setLabel(String s)
GetActionCommand()
SetLabel(String label)
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*
<applet code="MyApplet" width=200
height=300> </applet>
*/
public class MyApplet extends Applet
implements ActionListener
{
Button b1,b2,b3;
String msg="Welcome";
public void init()
{
b1=new Button("OK");
b2=new Button("Cancel");
b3=new Button("Exit");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
add(b1);

add(b2);
add(b3);
msg=b1.getLabel()+"
"+b2.getLabel()+"
"+b3.getLabel();
repaint();
}
public void actionPerformed(ActionEvent
ae)
{
if(ae.getSource()==b1)
msg=b1.getLabel();
if(ae.getSource()==b2)
msg=b2.getLabel();
if(ae.getSource()==b3)
msg=b3.getLabel();
//msg=x.getLabel();
msg=msg+" and Command
"+ae.getActionCommand();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,50,50);
}
}

Page - 5

Java Programming

TextField
A TextField is a scrollable text display object with one row of characters. The preferred width
of the field may be specified during construction and an initial string may be specified.
TextComponent is superclass of TextField and TextArea
GetSelectionStart()
getSelectionEnd()
TextField()

TextField(str)

TextField(col) TextField(str,col)

GetText()

SetText()

GetColumns()

SetColumns()

SetEchoChar()

GetEchoChar()

GetSelectedText()

SetSelectedText()

Select(start,end)

SetEditable(bool)

IsEditable()

Tips:
Call setEditable(false) to make the field read-only.
The constructor has an optional width parameter.
This does not control the number of characters in the TextField, but is merely a suggestion of
the preferred width on the screen. Note that layout managers may choose to respect or ignore
this preferred width.
For password fields:
field.setEchoChar('?');
To clear/reset:
field.setEchoChar((char)0);
CheckBoxes
Checkbox(String label, boolean b,CheckboxGroup cbg)
get CheckboxGroup()
getLabel()
getSelectedObject()
boolean getState()
set CheckboxGroup(CheckboxGroup cbg)
setLabel(String s)
setState(boolean b)

Page - 6

Java Programming

import java.awt.*;
import java.applet.Applet;
/*
<applet code="MyCheckbox2" width=300 height=200> </applet>
*/
public class MyCheckbox2 extends Applet {
public void init() {
Checkbox m1 = new Checkbox("Label1", true);
Checkbox m2 = new Checkbox("Label2", false);
Checkbox m3 = new Checkbox("Label3", true);
add(m1);
add(m2);
add(m3);
}
}
Radio Button
Checkbox getCurrent()
SetSelectedCheckbox(cb)

GetSelectedCheckbox()

Set current(Checkbox cb)

import java.awt.*;
import java.applet.Applet;
/*
<applet code="MyCheckboxGroup1" width=300 height=200> </applet>
*/
public class MyCheckboxGroup1 extends Applet {
public void init() {
// create button controller
CheckboxGroup cbg = new CheckboxGroup();
Checkbox cb1 =
new Checkbox("Show lowercase only", cbg, true);
Checkbox cb2 =
new Checkbox("Show uppercase only", cbg, false);
add(cb1);
add(cb2);
}
}

Page - 7

Java Programming

import java.awt.*;
import java.applet.Applet;
/*
<applet code="MyCheckboxGroup2" width=200 height=200> </applet>
*/
public class MyCheckboxGroup2 extends Applet {
CheckboxGroup cbg1,cbg2;
Checkbox cb1,cb2,cb3,cb4,cb5;
public void init() {
cbg1 = new CheckboxGroup();
cbg2 = new CheckboxGroup();
cb1 = new Checkbox("lowercase", cbg1, true);
cb2 = new Checkbox("uppercase", cbg1, false);
cb3 = new Checkbox("red", cbg2, true);
cb4 = new Checkbox("blue", cbg2, false);
cb5 = new Checkbox("greene", cbg2, false);
}
public void start()
{
add(cb1);
add(cb2);
add(cb3);
add(cb4);
add(cb5);
}
}
Choice

Add(str)
CountItems()
GetSelectedIndex()

Remove(str)
GetItem(index)
Insert(str,index)

import java.awt.*;
import java.applet.Applet;
/*<applet code="MyChoice1" width=300
height=200> </applet>*/
public class MyChoice1 extends Applet {
Choice rgb;
String s;
int i;
public void init() {
rgb = new Choice();
rgb.add("Red");
rgb.add("Green");
rgb.add("Blue"); }

AddItem(str)
GetItemCount()

public void start()


{
rgb.add("Magneta");
rgb.addItem("White");
rgb.insert("Five",2);
i=rgb.getItemCount();
s=rgb.getItem(3);
add(rgb);
}
public void paint(Graphics g)
{
g.drawString(s+", "+i,100,100);
} }
Page - 8

Java Programming

List() List(row)

List
List(row,bool multimode)

GetSelectedItem()
Add(str,index)

Select(index)

Scrollbar()

Add(str)
String[]
getSelectedItems()

Scrollbar
Scrollbar(int style,int initialvalue, int thumbsize,int min, int max)

SetValue(initval,thumb,m
in,max)
GetMinimum()
SetBlockIncrement(int)

GetSelectedIndex()
String[]
getSelectedIndexes()
GetItem(index)

GetValue()

SetValue(int)

GetMaximum()

SetUnitIncrement(int)

TextArea
TextArea()
TextArea(String text) TextArea(int row, int col)
TextArea(s,row,col,int scrollbar)

Appent(s)
GetRows()
GetScrollbarVisibility()

AppendText(s)
SetColumns()
Insert(s,pos)

TextArea(s,row,col)

GetColumns()
SetRows()
ReplaceRange(s,start,end)

SROLLBARS.BOTH/NONE/VERTICAL/HORIZONTAL
import java.awt.*;
import java.applet.Applet;
<applet code="MyTextArea1" width=300 height=200> </applet>
*/
public class MyTextArea1 extends Applet {
TextArea disp;
public void init() {
disp = new TextArea("Code goes here", 10, 30);
add(disp);
}
}

Page - 9

Java Programming

import java.awt.*;
import java.applet.Applet;
/*
<applet code="MyTextArea2" width=300 height=200> </applet>
*/
public class MyTextArea2 extends Applet {
String s =
"This is a very long message It should wrap when there is " +
"no horizontal scrollbar.";
public void init() {
add(new TextArea (s, 4, 15, TextArea.SCROLLBARS_NONE));
add(new TextArea (s, 4, 15, TextArea.SCROLLBARS_BOTH));
add(new TextArea (s, 4, 15,TextArea.SCROLLBARS_HORIZONTAL_ONLY));
add(new TextArea (s, 4, 15, TextArea.SCROLLBARS_VERTICAL_ONLY));
}
}
i import java.awt.*;
import java.applet.Applet;
/*
<applet code="DemoComponent1"
width=450 height=300> </applet>
*/
public class DemoComponent1 extends
Applet
{
String msg;
Button b1;
Label l1, l2;
TextArea ta;
TextField tf1,tf2;
public void init()
{
b1=new Button("OK");
l1=new Label("Name : ");
l2=new Label("Remarks : ");
tf1=new TextField(10);
tf2=new TextField(10);
ta=new TextArea("aaaa");
add(l1);
add(tf1);
add(l2);
add(tf2);
add(ta);
add(b1);

}
}
<html>
<title> My Components Demo </title>
<head> <h1>Here is coponents
Demo</h1> </head>
<body>
<BR><P>
<applet code="DemoComponent1"
width=400 height=250>
</applet>
</body>
</html>
--------------------------------------------------<html>
<title> My Components Demo </title>
<head> <h1>Here is coponents
Demo</h1> </head>
<body>
<BR><P>
<applet code="DemoComponent1"
width=400 height=200>
</applet>
<applet code="HelloWorld" width=400
height=75> </applet>
</body>
</html>

Page - 10

Java Programming

Text Editor
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="DemoTA" width=200 height=300> </applet>
*/
public class DemoTA extends Applet
implements ActionListener
{
int i,j;
String s="";
String s1="";
Button b1,b2;
Label msg;
TextArea ta;
public void init()
{
ta=new TextArea("Type here",20,50,0);
b1 = new Button("cut");
b1.addActionListener(this);
b2 = new Button("paste");
b2.addActionListener(this);
add(ta);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==b1)
{
s=ta.getSelectedText();
i=ta.getSelectionStart();
j=ta.getSelectionEnd();
ta.replaceRange("",i,j);}
if (ae.getSource()==b2)
{
i=ta.getSelectionStart();
j=ta.getSelectionEnd();
ta.replaceRange(s,i,j); }
repaint();
}
}

Page - 11

Java Programming

Canvas
A Canvas is a graphical component representing a region where you can draw things such as
rectangles, circles, and text strings. The name comes from a painter's canvas. You subclass
Canvas to override its default paint() method to define your own components.
You can subclass Canvas to provide a custom graphic in an applet.
import java.awt.Canvas;
import java.awt.Graphics;
class DrawingRegion extends Canvas {
public DrawingRegion() {
setSize(100, 50);
}
public void paint(Graphics g) {
g.drawRect(0, 0, 99, 49); // draw border
g.drawString("A Canvas", 20,20);
}
}
Then you use it like any other component, adding it to a parent container, for example in an
Applet subclass.
import java.applet.Applet;
public class CanvasPaintTest extends Applet {
public void init() {
DrawingRegion region = new DrawingRegion();
add(region);
}
The Canvas class is frequently extended to create new component types, for example image
buttons.

Page - 12

Java Programming

Working with Graphics


All graphics are drawn relative to an applet window. Left hand top corner of applet window is
0,0 in pixels.
Graphic class defines a number of drawing methods
import java.awt.*;
import java.applet.Applet;
/*
<applet code="DemoGraphics1" width=450 height=300> </applet>
*/
public class DemoGraphics1 extends Applet
{
public void paint(Graphics g)
{
g.drawLine(0,0,100,100);
g.drawLine(0,100,100,0);
}
}
import java.awt.*;
import java.applet.Applet;
/*
<applet code="DemoGraphics2" width=450 height=300> </applet>
*/
public class DemoGraphics2 extends Applet
{
public void paint(Graphics g)
{
g.drawRect(10,10,60,50);
g.fillRect(100,10,60,50);
g.drawRoundRect(190,10,60,50,15,15);
g.fillRoundRect(70, 90,140,100,30,40);
}
}
I

Page - 13

Java Programming

mport java.awt.*;
import java.applet.Applet;
/*
<applet code="DemoGraphics3" width=450 height=300> </applet>
*/
public class DemoGraphics3 extends Applet
{
public void paint(Graphics g)
{
g.drawOval(10,10,50,50);
g.fillOval(100,10,75,50);
g.drawArc(10,40,70,70,0,75);
g.fillArc(100,40,70,70,0,75);
}
}
import java.awt.*;
import java.applet.Applet;
/*
<applet code="DemoGraphics4" width=450 height=300> </applet>
*/
public class DemoGraphics4 extends Applet
{
public void paint(Graphics g)
{
int xpoints[]={30, 200,30,200,30};
int ypoints[]={30,30,200,200,30};
int num=5;
g.drawPolygon(xpoints, ypoints, num);
}
}

Page - 14

Java Programming

Images
import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="ImageDisplayer" width=300 height=300> </applet>
*/
/*
Applet needed to load media and text
Applet loaded from HTML file - getDocumentBase()
Applet loaded from class file - getCodeBase()
These method return values as URL objects
*/
public class ImageDisplayer extends Applet {
Image image;
public void init() {
image = getImage(getCodeBase(), "bsnllogo.gif");
}
public void paint(Graphics g) {
URL u=getCodeBase();
String msg="Codebase : "+u.toString();
g.drawString(msg,150,150);
//Draw image at its natural size first.
g.drawImage(image, 0, 0, this); //85x62 image
//Now draw the image scaled.
g.drawImage(image, 90, 0, 300, 62, this);
}
}

Page - 15

Java Programming

Working with Colors


The color class defines several methods to manipuate colors. import java.awt.*;
import java.applet.*;

g.drawRoundRect(190,10,60,50,15,15);

import java.awt.*;

g.fillRoundRect(70, 90,140,100,30,40);

/*

g.setColor(c3);

<applet code="DemoColors1" width=450


height=300> </applet>

g.drawOval(10,10,50,50);

*/

g.fillOval(100,10,75,50);

public class DemoColors1 extends Applet


{

g.drawArc(10,40,70,70,0,75);

public void paint(Graphics g)

g.fillArc(100,40,70,70,0,75);

{
Color c1=new Color(255, 100, 100);

g.setColor(Color.red);

Color c2=new Color(100,255, 100);


Color c3=new Color(100, 100,255);

int xpoints[]={30, 200,30,200,30};


int ypoints[]={30,30,200,200,30};

g.setColor(c1);

int num=5;

g.drawLine(0,0,100,100);
g.drawLine(0,100,100,0);

g.drawPolygon(xpoints, ypoints, num);

g.setColor(c2);

g.drawRect(10,10,60,50);

g.fillRect(100,10,60,50);

Page - 16

Java Programming

Working with Fonts


Fonts have family-name, logical font-name and face-name.
import java.applet.*;
import java.awt.*;
/*
<applet code="DemoFont1" width=450 height=300> </applet>
*/
public class DemoFont1 extends Applet
{
String msg;
Font f=new Font("Sans Serif", Font.BOLD, 18);
public void paint(Graphics g)
{
g.setColor(Color.green);
g.setFont(f);
msg="font : "+f.getFontName()+" size : "+f.getSize()+" style :
"+f.getStyle();
g.drawString("Demo of font class", 100, 50);
g.drawString(msg, 100, 75);
}
}

Page - 17

Java Programming

Event Handling in Java


Applets are event driven programs. Events will be mostly generated by user. There are
several types of events. Commonly handled events are generated by Mouse and Keyboard
and various controls like buttons etc.
Delegation event Model
The modern approach to handling events is based on Delegation event Model. Its concept is
quite simple :
A Source generates an event and sends it to one or more listeners.
The listener waits until it receives an event
Once received, the listener, process the event and returns.
Events
An event is an object that describes a state change in source. Eg. Mouse click, Key press ,
Counter exceeding a value, Timer expires etc..
You are free to define events that are appropriate to your application.
Event Source
A source is an object that generates an event. This occurs when internal state of object
changes in some way. A source can generate more than one events. A source must register
listeners in order for the listeners to receive notifications about a specific type of event.
Registration method is
Public void addTypeListener(TypeListener el)
Here type is the name of the event and el is reference to the event.
Examples :
The method that registers a keyboard event listener is called addKeyListener()
The method that registers a mouse motion listener is called addMouseMotionListener()
Event Listener
The listener is an object that is notified when an event occurs.
It has two major requirements
It must have been registered with one or more sources to receive notification about
specific type of event.
It must implement method to receive and process these notifications
The methods that receives and process events are defined in a set of interfaces found in
java.awt.event.
For example MouseMotionListener interface defines two methos to receive notifications
when the mouse is dragged or moved.

Page - 18

Java Programming

Example 1
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleButtonEvent1" width=200 height=300> </applet>
*/
public class SimpleButtonEvent1 extends Applet
implements ActionListener {
private Button b;
public void init() {
b = new Button("Press me");
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent e) {
// If the target of the event was our Button
// In this example, the check is not
// truly necessary as we only listen to
// a single button
if ( e.getSource() == b ) { //getSource() method returns the source of the event.
getGraphics().drawString("OUCH",20,20);
}
}
}

Page - 19

Java Programming

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleButtonEvent" width=200 height=300> </applet>
*/
public class SimpleButtonEvent extends Applet
implements ActionListener
{
Button b1,b2,b3;
String msg="";
public void init()
{
b1 = new Button("Yes");
b2 = new Button("No");
b3 = new Button("May be");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
add(b1);
add(b2);
add(b3);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Yes"))
{msg="You pressed Yes";}
else if(str.equals("No"))
{msg="You pressed No";}
else
{msg="You pressed May be";}
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,6,100);
}
}

Page - 20

Java Programming

Handling Mouse Events


To handle mouse events you must implement MouseListener and MouseMotionListener
interface.
In following example following is displayed with mouse events
Button pressed
Button released
Button clicked
Mouse pointer enters
Mouse pointer exited

Down
Up
Mouse clicked
Entered
Exited

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="MouseEvents" width=400 height=300> </applet>
*/
public class MouseEvents extends Applet implements MouseListener,
MouseMotionListener
{
String msg=;
int mouseX=0, mouseY=0; //co-ordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse Clicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse entered";
repaint();
}

Page - 21

Java Programming

public void mouseExited(MouseEvent me)


{
mouseX=0;
mouseY=10;
msg="Mouse exited";
repaint();
}
public void mousePressed(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="*";
showStatus("Dragging mouse at "+mouseX+","+mouseY);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving mouse at "+me.getX()+","+me.getY());
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, mouseX,mouseY);
}
}

Page - 22

Java Programming

LayOut Manager
Java has GUI Component placement strategy. Since java uses native windowing system to
provide its windows & button building blocks, It is not possible to specify component
dimensions & positions with absolute precision.
AWT uses automatic layout system based on layout managers with
Flowlayout
GridLayout
BorderLayout
GridbagLayout
CardLayout
FlowLayout
A flow layout arranges components in a left-to-right flow, much like lines of text in a
paragraph. Flow layouts are typically used to arrange buttons in a panel. It will arrange
buttons left to right until no more buttons fit on the same line. Each line is centered.
A flow layout lets each component assume its natural (preferred) size.
GridLayout
The GridLayout class is a layout manager that lays out a container's components in a
rectangular grid.
The container is divided into equal-sized rectangles, and one component is placed in each
rectangle.
Add gridlayout manager (replacing default flowlayout manager) in the init() method before
putting any control to the layout with setLayout() method.
For example, the following is an applet that lays out six buttons into three rows and two
columns:
FlowLayout
import java.awt.*;
import java.applet.Applet;
public class myButtons extends Applet {
Button button1, button2, button3;
public void init() {
button1 = new Button("Ok");
button2 = new Button("Open");
button3 = new Button("Close");
add(button1);
add(button2);
add(button3);
}
}

GridLayout
import java.awt.*;
import java.applet.Applet;
public class ButtonGrid extends Applet {
public void init() {
setLayout(new GridLayout(3,2));
add(new Button("1"));
add(new Button("2"));
add(new Button("3"));
add(new Button("4"));
add(new Button("5"));
add(new Button("6"));
}
}

Page - 23

Java Programming

When both the number of rows and the number of columns have been set to non-zero values,
either by a constructor or by the setRows and setColumns methods, the number of columns
specified is ignored. Instead, the number of columns is determined from the specified number
or rows and the total number of components in the layout. So, for example, if three rows and
two columns have been specified and nine components are added to the layout, then they will
be displayed as three rows of three columns. Specifying the number of columns affects the
layout only when the number of rows is set to zero
import java.awt.*;
import java.applet.Applet;

fill5=new Label();
add(fill5);
text2=new TextField(10);
add(text2);
fill6=new Label();
add(fill6);
spacer1=new Label();
add(spacer1);
spacer2=new Label();
add(spacer2);
spacer3=new Label();
add(spacer3);
fill7=new Label();
add(fill7);
b1=new Button("=");
add(b1);
fill8=new Label();
add(fill8);
spacer4=new Label();
add(spacer4);
spacer5=new Label();
add(spacer5);
spacer6=new Label();
add(spacer6);
fill9=new Label();
add(fill9);
answertext=new TextField(10);
add(answertext);
fill10=new Label();
add(fill10);

/*
<applet code="MyGridLayout1"
width=300 height=200> </applet>
*/
public class MyGridLayout1 extends
Applet {
TextField text1,text2,answertext;
Label pluslabel, fill1, fill2, fill3,
fill4, fill5, fill6, fill7, fill8, fill9, fill10;
Label spacer1, spacer2, spacer3,
spacer4, spacer5, spacer6;
Button b1;
public void init() {
setLayout(new GridLayout(9,3));
fill1=new Label();
add(fill1);
text1=new TextField(10);
add(text1);
fill2=new Label();
add(fill2);
fill3=new Label();
add(fill3);
pluslabel=new
Label("+",Label.CENTER);
add(pluslabel);
fill4=new Label();
add(fill4);

}
}

Page - 24

Java Programming

BorderLayout
The BorderLayout positions and scales components along left, right, top, bottom & center
edges of window. It allows you to surround applet with scroll bars
import java.applet.Applet;
import java.awt.*;
/*
<applet code="MyBorderLayout" width=300 height=200> </applet>
*/
public class MyBorderLayout extends Applet
{
Scrollbar hScroll1, hScroll2, vScroll1, vScroll2;
Button b1;
public void init()
{
setLayout(new BorderLayout());
b1=new Button("Hello");
hScroll1=new Scrollbar(Scrollbar.HORIZONTAL,1,1,1,200);
hScroll2=new Scrollbar(Scrollbar.HORIZONTAL,1,1,1,200);
vScroll1=new Scrollbar(Scrollbar.VERTICAL,1,1,1,200);
vScroll2=new Scrollbar(Scrollbar.VERTICAL,1,1,1,200);
add("North",hScroll1);
add("South",hScroll2);
add("West",vScroll1);
add("East",vScroll2);
add("Center",b1);
}
}

Page - 25

Java Programming

GridBag Layout
It uses helper class GridBagConstraints to specify all layout parameter.
It has advantage of allowing component to use up more than one grid cell.
Componenet size can be specified by
Number of horizontals and or
Number of vertical grid cell
Componenet placement and size is controlled by gridx, gridy, gridwidth and gridheight
variables
Example GridBagLayout
Show 9 buttons in one row
Show 9 buttons in three row
Skip one button with gridx++;
Gbc.fill=GridBagConstraints.HORIZONTAL / VERTICAL / BOTH
Gbc.weightx =5/ weighty=5
Gbc.gridwidth=GridBagConstraints.REMAINDER
Example
import java.awt.*;
import java.applet.*;
/*
<applet code="MyGridBag1" width=300 height=200>
</applet>
*/
public class MyGridBag1 extends Applet
{
public void init()
{
GridBagLayout gb=new GridBagLayout();
GridBagConstraints gbc=new
GridBagConstraints();
Button b1,b2,b3,b4,b5,b6;
setLayout(gb);
gbc.gridwidth=1;
gbc.gridheight=1;
gbc.gridx=0;
gbc.gridy=0;
gbc.fill=GridBagConstraints.HORIZONTAL;
b1=new Button("FIrst");
add(b1,gbc);
b2=new Button("Second");
gbc.gridx=1;
gbc.gridwidth=2;
add(b2,gbc);
Page - 26

Java Programming

b3=new Button("Third");
gbc.gridx=3;
gbc.gridwidth=GridBagConstraints.REMAINDER;
add(b3,gbc);
b4=new Button("Fourth");
gbc.gridy++;
gbc.gridx=0;
add(b4,gbc);
b5=new Button("Fifth");
gbc.gridy++;
gbc.gridx=0;
gbc.gridwidth=1;
add(b5,gbc);
b6=new Button("Sixth");
gbc.gridx=1;
gbc.gridwidth=GridBagConstraints.REMAINDER;
add(b6,gbc);
}
}
import java.awt.*;
import java.applet.*;
/*<applet code = "MyGridbagLayout1" width=500 height=300> </applet>*/
public class MyGridbagLayout1 extends Applet
{
Button b1,b2,b3,b4,b5,b6,b7,b8,b9;
GridBagLayout gb=new
GridBagLayout();
GridBagConstraints gbc=new
GridBagConstraints();
public void init()
{
setLayout(gb);
gbc.weightx=5;
gbc.weighty=5;
gbc.fill=GridBagConstraints.HORIZONTAL;
b1=new Button("First Button");
add(b1,gbc);
b2=new Button("Second");
add(b2,gbc);
b3=new Button("3rd");
add(b3,gbc);
gbc.gridy=2;
b4=new Button("Forth");
add(b4,gbc);
Page - 27

Java Programming

gbc.gridx=2;
b5=new Button("Fifth Button");
add(b5,gbc);
b6=new Button("Sixth");
//add(b6,gbc);
gbc.gridy++;
gbc.gridx=0;
b7=new Button("Seventh");
add(b7,gbc);
gbc.gridx++;
gbc.gridwidth =
GridBagConstraints.REMAINDER;
b8=new Button("Eighth");
add(b8,gbc);
gbc.gridx++;
b9=new Button("Ninth");
add(b9,gbc);
}
}

Page - 28

Java Programming

Card Layout Manager


import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*
<applet code="CardTest" height=300 width=300></applet>
*/
public class CardTest extends Applet
implements ActionListener,
ItemListener {
CardPanel cards;
public CardTest() {
setLayout(new BorderLayout());
add("Center", cards = new CardPanel(this));
Panel p = new Panel();
p.setLayout(new FlowLayout());
add("South", p);
Button b = new Button("first");
b.addActionListener(this);
p.add(b);
b = new Button("next");
b.addActionListener(this);
p.add(b);
b = new Button("previous");
b.addActionListener(this);
p.add(b);
b = new Button("last");
b.addActionListener(this);
p.add(b);
Choice c = new Choice();
c.addItem("one");
c.addItem("two");
c.addItem("three");
c.addItem("four");
c.addItem("five");
c.addItem("six");
c.addItemListener(this);
p.add(c);
}
public void itemStateChanged(ItemEvent e) {
((CardLayout)cards.getLayout()).show(cards,
Page - 29

Java Programming

(String)(e.getItem()));
}
public void actionPerformed(ActionEvent e) {
String arg = e.getActionCommand();
if ("first".equals(arg)) {
((CardLayout)cards.getLayout()).first(cards);
} else if ("next".equals(arg)) {
((CardLayout)cards.getLayout()).next(cards);
} else if ("previous".equals(arg)) {
((CardLayout)cards.getLayout()).previous(cards);
} else if ("last".equals(arg)) {
((CardLayout)cards.getLayout()).last(cards);
} else {
((CardLayout)cards.getLayout()).show(cards,(String)arg);
}
}
public static void main(String args[]) {
Frame f = new Frame("CardTest");
CardTest cardTest = new CardTest();
cardTest.init();
cardTest.start();
f.add("Center", cardTest);
f.setSize(300, 300);
f.show();
}
public String getAppletInfo() {
return "Demonstrates the different types of layout
managers.";
}
}
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*<applet code="CardPanel" height=300 width=300></applet>*/
class CardPanel extends Panel {
ActionListener listener;
Panel create(LayoutManager layout) {
Button b = null;
Page - 30

Java Programming

Panel p = new Panel();


p.setLayout(layout);
b = new Button("one");
b.addActionListener(listener);
p.add("North", b);
b = new Button("two");
b.addActionListener(listener);
p.add("West", b);
b = new Button("three");
b.addActionListener(listener);
p.add("South", b);
b = new Button("four");
b.addActionListener(listener);
p.add("East", b);
b = new Button("five");
b.addActionListener(listener);
p.add("Center", b);
b = new Button("six");
b.addActionListener(listener);
p.add("Center", b);
return p;
}
CardPanel(ActionListener actionListener) {
listener = actionListener;
setLayout(new CardLayout());
add("one", create(new FlowLayout()));
add("two", create(new BorderLayout()));
add("three", create(new GridLayout(2, 2)));
add("four", create(new BorderLayout(10, 10)));
add("five", create(new FlowLayout(FlowLayout.LEFT, 10, 10)));
add("six", create(new GridLayout(2, 2, 10, 10)));
}
public Dimension getPreferredSize() {
return new Dimension(200, 100);
}
}

Page - 31

Java Programming

Chapter - 9
AWT Applications

Objectives :
At the end of this chapter

You will understand the concepts of Windows, Frames, Panels

You will be able to write programs for Java Application using Windows,
Frames and Panels

Super classes can be extended and their properties can be inherited. Component is an
abstract subclass of main class Container. Container has add() method. It has subclasses
Window, Panel.
Window : Has subclass a frame which is a window with Title & resizing corners.
In frames the default layout manager is BorderLayout.
You must change it using setLayout()
Initially frame is invisible despite of all components added to it. Use setVisible(true)
Draw a frame and set foreground / background colors and display text.
import java.awt.*;
public class DrawFrame1
{
private Frame f;
private Label l;
public void launchFrame()
{
l=new Label("Good Day");
f=new Frame("Hello Friends");
f.setSize(150,150);
f.setBackground(Color.blue);
f.setForeground(Color.red);
f.add(l);
f.setVisible(true);
}
public static void main(String args[])
{
DrawFrame1 f=new DrawFrame1();
f.launchFrame();
}
}
Page - 32

Java Programming

import java.awt.*;
public class FrameWithPanel
{
private Frame f;
private Panel p;
public FrameWithPanel(String title)
{
f=new Frame(title);
p=new Panel();
}
public void launchFrameWithPanel()
{
f.setSize(200,200);
f.setBackground(Color.blue);
f.setLayout(null);
p.setSize(100,100);
p.setBackground(Color.red);
f.add(p);
f.setVisible(true);
}
public static void main(String args[])
{
FrameWithPanel guiWindow=new FrameWithPanel("Frame with Panel");
guiWindow.launchFrameWithPanel();
}
}

Page - 33

Java Programming

Panels

Provides space for components.


Allows sub-panel to have their own layout manager. DrawFrame1 guiWindow=new
DrawFrame1();
guiWindow.launchFrame();
}

}
One frame with two panels
import java.awt.*;
public class FrameWithPanel1
{
private Frame f;
private Panel p,p1;
private Label l,l1;
Button b,b1;
public FrameWithPanel1(String title)
{
f=new Frame(title);
p=new Panel();
l=new Label("Hello Friends How r u");
p1=new Panel();
l1=new Label("Message on second panel");
b=new Button("OK");
b1=new Button("Cancel");
}
public void launchFrameWithPanel1()
{
f.setSize(200,200);
//f.setBackground(Color.blue);
f.setLayout(new FlowLayout());

p.setSize(100,100);
p1.setSize(100,100);
p.setBackground(Color.red);
p.setForeground(Color.blue);
p.add(l);
p.add(b);
p1.setBackground(Color.yellow);
p1.setForeground(Color.red);
p1.add(l1);
p1.add(b1);
f.add(p);
f.add(p1);
f.setVisible(true);
}
public static void main(String args[])
{
FrameWithPanel1 guiWindow=new
FrameWithPanel1("Frame with Panel");
guiWindow.launchFrameWithPanel1();
}
}

Page - 34

S-ar putea să vă placă și