AWT
--
Abstract Window Toolkit
- it contains
numerous classes and methods that allow you
to create and
manage windows.
- main purpose of
the AWT is to support applet windows
- package
java.awt.*
java.awt.event.*
Event:
-----
state change in a
source
source:
-------
it is an object
that generates an event.
Listener:
-------
is an object that
is notified when an event occurs.
method:
--------
public void
addTypeListener(TypeEvent object)
Components of
AWT:
-----------------------
1)Button
2)Label
3)TextField
4)TextArea
5)Choice
6)List
7)Checkbox
8)Menu
Event Class:
--------------
1)ActionEvent -
button,list,menu
2)AdjustmentEvent
- scrollbar
3)ItemEvent -
checkbox,list
4)KeyEvent -
keyboard
5)MouseEvent -
mouse
Adding and Removing Controls
-----------------------------------
To include a control in a window, we must add it to the
window.
syntax:
Component
add(Component compObj)
Here, compObj
is an instance of the control that we want to add. A reference to compObj is returned. Once a control has been added, it will
automatically be visible whenever its parent window is displayed.
void
remove(Component obj)
Here, obj is
a reference to the control we want to remove.
we can remove all controls by
calling removeAll().
Label:
------
constructors:
--------------
Label();
Label(String);
Label(String,int
how);
The first version
creates a blank label. The second
version creates a label that contains the string specified by str. This string is left justified. The third version creates a label that
contains the string specified by str using the alignment specified by how. The value of how must be one of these three
constants:
Label.LEFT,Label.RIGHT,Label.CENTER.
method
-----
void
setText(String str) - str specifies the
new label.
String
getText() - the current label is returned.
we can set the alignment of the string within the label by
calling setAlignment().
void setAlignment(int how)
To obtain the current alignment, call getAlignment().
int
getAlignment()
ex:
import
java.awt.*;
import java.applet.*;
//<applet code=LabelDemo width=300
height=300></applet>
public class LabelDemo extends Applet
{
public void
init(){
Label
one=new Label("One");
Label
two=new Label("Two");
Label
three=new Label("Three");
//add
labels to applet window
add(one);
add(two);
add(three);
}
}
Using Buttons
--------------
Button
-------
Constructors:
--------------
Button();
creates an empty button.
Button(String
str);
this contains str
as a label.
Methods:
----------
void setLabel(String str); -becomes the new label for the
button.
String getLabel(); -
retrieve its label by calling getLabel().
Handling Buttons
----------------
Each listener implements the ActionListener interface. The interface defines the actionPerformed()
method, which is called when an event occurs.
The label is obtained by calling the getActionCommand()
method on the ActionEvent object passes to actionPerformed().
Listener:
--------
1)ActionListener
public void
actionPerformed(ActionEvent ae)
{
statements;
}
getActionCommand() - to know the label of the button("Ok")
getSource(); - to
know the variable name of the button(b1,b2)
ex:
import
java.awt.*;
import
java.awt.event.*;
import java.applet.*;
//<applet code=ButtonDemo width=300
height=300></applet>
public class ButtonDemo extends Applet implements
ActionListener
{
String
msg="";
Button
b1,b2,b3;
public void
init()
{
b1=new
Button("Yes");
b2=new
Button("No");
b3=new
Button("Undecided");
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
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 Undecided.";
repaint();
}
public void
paint(Graphics g){
g.drawString(msg,5,100);
}
}
Using a TextField
----------------
TextField() - creates a default text field.
TextField(int numChars)
Creates a
textfield that is numChars characters wide.
TextField(String str)
initializes
the text field with the string contained in str.
TextField(String str,int numChars)
initializes
the text field and sets its width.
String getText() -
The string currently contained in the text field
void setText(String str) -
To set the Text
str is the new string
String getSelectedText() - returns the selected text.
void select(int startIndex,int endIndex) - selects
the characters
beginning at startIndex and ending at endIndex-1.
boolean isEditable()
- returns true if the text may be changed and false if not.
void setEditable(boolean canEdit)
- if canEdit is true, the text may be changed. If it is false, the text
cannot be altered.
void setEchoChar(char ch)
boolean echoCharIsSet()
char getEchoChar()
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=TextFieldDemo width=200
height=200></applet>
public class TextFieldDemo extends Applet implements
ActionListener{
TextField
name,pass;
public void
init(){
Label
name1=new Label("Name :",Label.RIGHT);
Label
pass1=new Label("Password :",Label.RIGHT);
name=new
TextField(12);
pass=new
TextField(8);
pass.setEchoChar('?');
add(name1);
add(name);
add(pass1);
add(pass);
name.addActionListener(this);
pass.addActionListener(this);
}
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);
}
}
exercise:
pro1:
import
java.awt.*;
import
java.applet.*;
import java.awt.event.*;
//<applet code=passw.class width=200
height=200></applet>
public class passw extends Applet implements ActionListener
{
TextField
t1,t2;
public void
init(){
t1=new
TextField(30);
add(t1);
t2=new
TextField(30);
add(t2);
t1.setEchoChar('@');
t1.addActionListener(this);
}
public void
actionPerformed(ActionEvent a)
{
if(a.getSource()==t1)
t2.setText(t1.getText());
}
}
prg:2
import
java.applet.*;
import
java.awt.*;
import
java.awt.event.*;
/*<applet code=applet1.class width=100
height=200></applet>*/
public class applet1 extends Applet implements
ActionListener
{
TextField
text1;
Button b1;
public void
init()
{
text1=new
TextField(25);
add(text1);
b1=new
Button("Click me");
add(b1);
b1.addActionListener(this);
}
public void
actionPerformed(ActionEvent e)
{
String
msg=new String("Hello Friends");
if(e.getSource()==b1)
text1.setText(msg);
}
}
Checkbox:
---------
Constructors:
-------------
Checkbox();
label is
initially blank. The state of the check
box is unchecked.
Checkbox(String
str);
create
a checkbox whose label is specified by str.
The state of the check box is unchecked.
Checkbox(String,boolean on);
Allows to set
the initial state of the check box . If
on is true, the check box is initially checked;otherwise, it is cleared.
Checkbox(String,boolean on,CheckboxGroup cbg);
Checkbox(String,CheckboxGroup cbg,boolean on);
Methods:
------
boolean
getState(); - Current state of a check box
void
setState(boolean); - To set its state
String
getLabel();
void setLabel(String
str);
Handling Check Boxes
=====================
Each listener implements the ItemListener interface. That interface defines the itemStateChanged()
method.
ItemListener:
------------
void
itemStateChanged(ItemEvent ie)
{
statements;
}
import
java.awt.*;
import
java.awt.event.*;
import
java.applet.*;
//<applet code=CheckboxDemo width=300
height=300></applet>
public class CheckboxDemo extends Applet implements
ItemListener{
String
msg="";
Checkbox
c1,c2,c3,c4;
public void
init(){
c1=new
Checkbox("Window 98",true);
c2=new
Checkbox("Windows NT");
c3=new
Checkbox("Solaris");
c4=new
Checkbox("Macos");
add(c1);
add(c2);
add(c3);
add(c4);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
}
public void
itemStateChanged(ItemEvent ie){
repaint();
}
public void
paint(Graphics g){
msg="Current State : ";
g.drawString(msg,6,70);
msg="Windows
98: "+c1.getState();
g.drawString(msg,6,90);
msg="Windows
NT: "+c2.getState();
g.drawString(msg,6,110);
msg="Solaris
: "+c3.getState();
g.drawString(msg,6,130);
msg=":Macos
: "+c4.getState();
g.drawString(msg,6,150);
}
}
CheckboxGroup
=============
one and only one check box in the group can be checked at
any one time. These check boxes are
often called radio buttons.
method
------
Checkbox getSelectedCheckbox() - which check box in a group
is currently selected.
void setSelectedCheckbox(Checkbox which)
which is the
check box that we want to be selected.
import
java.awt.*;
import
java.awt.event.*;
import java.applet.*;
//<applet code=CBGroup width=300
height=300></applet>
public class CBGroup extends Applet implements ItemListener{
String
msg="";
Checkbox
c1,c2,c3,c4;
CheckboxGroup
cbg;
public void
init(){
cbg=new
CheckboxGroup();
c1=new
Checkbox("Window 98",cbg,true);
c2=new
Checkbox("Windows NT",cbg,false);
c3=new
Checkbox("Solaris",cbg,false);
c4=new
Checkbox("Macos",cbg,false);
add(c1);
add(c2);
add(c3);
add(c4);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
}
public void
itemStateChanged(ItemEvent ie){
repaint();
}
public void
paint(Graphics g){
msg="Current
Selection : ";
msg+=cbg.getSelectedCheckbox().getLabel();
g.drawString(msg,6,70);
}
}
Choice Controls
===============
The Chocie class is used to create a pop-up list
of items from which the user may choose.
method
========
void addItem(String name)
void add(String name)
Here, name is the name of the item being added. Items are added to the list in the order in
which calls to add() or addItem() occur.
String getSelectedItem()
which item is currently selected.
int getSelectedIndex() - returns the index of the item. The first item is at index 0. By default, the first item added to the list
is selected.
int getItemCount() To
obtain the number of items in the list
void select(int index)
void select(String name)
import
java.awt.*;
import
java.awt.event.*;
import java.applet.*;
//<applet code=ChoiceDemo width=300
height=300></applet>
public class ChoiceDemo extends Applet implements
ItemListener{
Choice
os,browser;
String
msg="";
public void
init()
{
os=new
Choice();
browser=new
Choice();
//add
items to os list
os.add("Windows
98");
os.add("Windows
NT");
os.add("Unix");
os.add("Linux");
//add
items to broswer list
browser.add("Netscape
1.1");
browser.add("Netscape
2.x");
browser.add("Netscape
3.x");
browser.add("Netscape
4.x");
browser.add("Internet
Explorer 2.0");
browser.add("Internet
Explorer 3.0");
browser.add("Internet
Explorer 4.0");
browser.select("Netscape
3.x");
//add
choice lists to window
add(os);
add(browser);
//register
to receive item events
os.addItemListener(this);
browser.addItemListener(this);
}
public void
itemStateChanged(ItemEvent ie){
repaint();
}
//Display
current selections.
public void
paint(Graphics g){
msg="Current
OS :";
msg+=os.getSelectedItem();
g.drawString(msg,6,120);
msg="Current Browser:";
msg+=browser.getSelectedItem();
g.drawString(msg,6,140);
}
}
List:
-----
Multiple-choice, scrolling selection list.
Constructors:
------------
List();
Allows only one
item to be selected at any one time.
List(int
numRows);
numRows specifies
the number of entries in the list that will always be visible.
List(int
numRows,boolean multipleSelect);
if multipleSelect
is true, then the user may select two or more items at a time.
Methods:
-------
add(String name);
Here name is the
name of the item added to the list. This
form adds items to the end of the list.
add(String
name,int index);
adds the item at
the index specified by index. indexing begins at zero.
we can
specify -1 to add the item to the end of
the list.
String getSelectedItem();
returns a string containing the name of the item. If more than one item is selected or if no
selection has yet been made, null is returned.
int getSelectedIndex(); - returns the index of the item.
int
getItemCount();
//Demonstrate Lists.
import java.awt.*;
import
java.awt.event.*;
import
java.applet.*;
//<applet code=ListDemo wisth=300
height=300></applet>
public class ListDemo extends Applet implements
ActionListener{
List
os,browser;
String
msg="";
public
void init()
{
os=new
List(4,true);
browser=new
List(4,false);
//add
items to os list
os.add("Windows
98");
os.add("Windows
NT");
os.add("Unix");
os.add("Linux");
//add
items to broswer list
browser.add("Netscape
1.1");
browser.add("Netscape
2.x");
browser.add("Netscape
3.x");
browser.add("Netscape
4.x");
browser.add("Internet
Explorer 2.0");
browser.add("Internet
Explorer 3.0");
browser.add("Internet
Explorer 4.0");
browser.select(2);
//add
choice lists to window
add(os);
add(browser);
//register
to receive item events
os.addActionListener(this);
browser.addActionListener(this);
}
public
void actionPerformed(ActionEvent ae){
repaint();
}
//Display
current selections.
public
void paint(Graphics g){
int
idx[];
msg="Current
OS :";
idx=os.getSelectedIndexes();
for(int
i=0;i<idx.length;i++)
msg+=os.getItem(idx[i])+"
";
g.drawString(msg,6,120);
msg="Current Browser:";
msg+=browser.getSelectedItem();
g.drawString(msg,6,140);
}
}
TextField:
-----------
constructors:
---------------
TextField();
TextField(int no.
of characters);
TextField(String);
TextField(String,int no. of characters);
Methods:
---------
getText();
setText(String);
select(int
startindex,int endindex);
getSelectedText();
setEditable(boolean);
isEditable();
setEchoChar(char);
echoCharIsSet();
getEchoChar();
Choice:
------
Constructors:
------------
Choice();
To add elements
to choice list:
-------------------------------
addItem(String);
add(String);
Methods:
-------
String
getSelectedItem();
int getSelectedIndex();
int
getItemCount();
void select(int
index);
void
select(String);
void getItem(int
index);
Scrollbar:
-----------
constructors:
------------
Scrollbar();
Scrollbar(int
style);
Scrollbar(int
style,int initial value,int thumbsize,int min,int max);
style:
-----
Scrollbar.HORIZONTAL
Scrollbar.VERTICAL
METHODS:
--------------
void
setValues(int initialvalue,int thumbsize,int min,int max);
int getValue();
void setValue(int
newvalue);
int getMinimum();
int getMaximum();
void
setUnitIncrement(int value);
void
setBlockIncrement(int value);
KeyEvent Class:
---------------
types of
keyEvent:
--------------
KEY_PRESSED
KEY_RELEASED
KEY_TYPED
OTHER KEY
Constants:
--------------------
VK_0 through VK_9
VK_A through VK_Z
VK_ENTER
VK_ESCAPE
VK_CANCEL
VK_UP
VK_DOWN
VK_LEFT
VK_RIGHT
VK_PAGEDOWN
VK_PAGEUP
VK_SHIFT
VK_ALT
VK_CONTROL
VK -Virtual Key
code
independent
of any modifiers such as Ctrl,Alt and shift
Methods:
---------
char getKeyChar();
int getKeyCode();
KeyListener:
--------------
void
keyPressed(KeyEvent ke)
void
keyReleased(KeyEvent ke)
void
keyTyped(KeyEvent ke)
Frame:
------
* it is a new
window
Constructors:
------------
Frame();
Frame(String
title);
Hiding and showing
a window:
----------------------
setVisible(boolean visibleflag);
Setting window's
Title:
--------------
setTitle(String
new title);
To hide a window:
----------
setVisible(false);
To close a window
-------------------
System.exit(0);
To set the size
---------------
setSize(int,int);
Layout:
------
To arranging the
AWT components
Layout is set by
the following method
void
setLayout(LayoutManager layoutobject);
Types:
------
Flow Layout (Left top right bottom)
Border
Layout (N,E,S,W,C)
Grid Layout (Row & Column manner)
GridBag (Always in the screen's center)
Panel (to group the components)
Flow Layout:
-------------
constructors:
-----------
FlowLayout();
FlowLayout(int
how);
FlowLayout(int
how,int horizontal,int Vertical);
how:
----
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
Border Layout:
-----------------------
constructors:
--------------
BorderLayout();
BorderLayout(int horz,int vert);
To add the component in the Border Layout:
----------------------------------------------------------
void add(Component object,object region);
Region:
--------
BorderLayout.CENTER
BorderLayout.EAST
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.WEST
Insets:
-------
used to leave a small amount of space between the container
that holds your
components and the window that contains it.
constructor:
--------------
Insets(int top,int left,int bottom,int right);
Method:
--------
Insets getInsets();
Grid Layout:
----------------
constructors:
----------------
GridLayout();
GridLayout(int no.of rows,int no. of columns);
GridLayout(int no.of rows,int no. of columns,int hor,in
vert);
CardLayout:
-----------------
constructor:
-------------
CardLayout();
CardLayout(int horz,int vert);
Cards are added into panel by the following method:
void add(Component panelobject,objectname);
Methods:
---------
void first(Container deck);
void last(Container deck);
void next(Container deck);
void previous(Container deck);
void show(Container deck,String cardname);
TextArea:
---------
constructors:
----------
TextArea();
TextArea(int num.
of lines,int no. of characters);
TextArea(String);
TextArea(String,int no. of lines,int no. of characters);
TextArea(String,int no. of lines,int no. of characters,int scrollbars);
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
Methods:
-------
getText();
setText(String);
getSelectedText();
select(int start
index,int end index);
setEditable(boolean);
append(String);
insert(String,int
index);
replaceRange(String str,int startindex,int endindex);
MenuBar and Menu:
---------------
Constructors of Menu:
--------------------
Menu();
Menu(String optionname);
Menu(String optionname,boolean removable);
Constructors of MenuItem:
--------------------------
MenuItem();
MenuItem(String itemname);
MenuItem(String itemname,MenuShortcut keyAccel);
Menuitem can be disable or enabled by
----------
void setEnabled(boolean enabledflag);
name of the menuitem can be changed by
-------------------------------
void setLabel(String newname);
String getLabel();
add(menuitem);
add(menu);
To add the Menubar into the Frame
----------------------------------
setMenubar(menubar);
FileDialog:
-----------
* built in dialog box
Constructors:
-----------
FileDialog(Frame parent,String boxname);
FileDialog(Frame parent,String boxname,int how);
FileDialog(Frame parent);
how:
----
FileDialog.LOAD(To read)
FileDialog.SAVE(To write)
Methods:
--------
String getDirectory();
String getFile();
DialogBox:
-----------
* Used to hold a set of related controls.
* it can be modal or modeless.
modal - other parts of program is not active and not
accessible
modeless - other parts of program is active and accessible
constructors:
-----------
Dialog(Frame
parent,boolean mode);
Dialog(Frame parent,String title,boolean mode);
To close a dialog box:
---------------------
dispose(); - it frees all system resources associated with
the
dialog box window.
Applet
-----
* it is a window to hold the awt components
* life cycle
init
start
paint
stop
destroy
<applet
code ="program name"
height="200"
width="300"
>
</applet>
to run
--------
appletviewer filename.java
MouseListener
----------------
Entered
Exited
Pressed
Released
Clicked
MouseMotionListener
-------------------
MouseMoved
MouseDragged
===============
TextArea()
TextArea(int numLines,int numChars)
TextArea(String str)
TextArea(String str,int numLines,int numChars)
TextArea(String str,int numLines,int numCharas,int sBars)
numLines - specifies the height
numChars - specifies the width
sBars -Scrollbars
SCROLLBARS_BOTH
SCROLLBARS_VERTICAL_ONLY
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_NONE
import java.awt.*;
import
java.awt.event.*;
import
java.applet.*;
//<applet code=TextAreaDemo width=200
height=200></applet>
public class TextAreaDemo extends Applet{
public void
init()
{
String
val="That's why TextPad is so popular. "+"\nWhether you simply
need a powerful replacement for Notepad,"+"\n a tool for editing your
web pages, or "+"\na programming IDE, TextPad does what you want"+"\n,
the way you would expect.";
TextArea
text=new TextArea(val,10,50);
add(text);
}
}
Managing Scroll Bars
------------------------
Scrollbar()
Create a
vertical scroll bar.
Scrollbar(int style)
Scrollbar(int style,int initialValue,int thumbSize,int
min,int max)
If style is
Scrollbar.VERTICAL
Scrollbar.HORIZONTAL
void setValues(int initialValue,int thumbSize,int min,int
max)
To obtain the current value of the scrollbar, call
int getValue(). It returns the current setting.
To set the current value
void
setValue(int newValue)
int getMinimum()
int getMaximum()
They returns the requested quantity.
void setUnitIncrement(int newIncr)
void setBlockIncrement(int newIncr)
Handling Scroll Bars
------------------------
implement the AdjustmentListener interface.
The AdjustmentListener interface has only one method,
adjustmentValueChanged:
void
adjustmentValueChanged(AdjustmentEvent e)
getAdjustmentType() method used to determine the type of the
adjustment.
Adjustable getAdjustable() Get
the adjustable object where this event originated.
Scroll.java
import
java.applet.*;
import
java.awt.event.*;
import
java.awt.*;
/*
<APPLET
CODE=scroll.class
WIDTH=400
HEIGHT=100
>
</APPLET>
*/
public class scroll extends Applet implements
AdjustmentListener
{
TextField
text1;
Scrollbar
hscroll,vscroll;
public void
init()
{
hscroll=new
Scrollbar(Scrollbar.HORIZONTAL,10,10,1,200);
add(hscroll);
hscroll.addAdjustmentListener(this);
text1=new
TextField(25);
add(text1);
vscroll=new
Scrollbar(Scrollbar.VERTICAL,1,20,1,200);
add(vscroll);
vscroll.addAdjustmentListener(this);
}
public void
adjustmentValueChanged(AdjustmentEvent e)
{
if(e.getAdjustable()==hscroll||e.getAdjustable()==vscroll)
{
text1.setText("Horizontal:"+hscroll.getValue()+"
Vertical:"+vscroll.getValue());
}
}
}
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<applet code=SBDemo width=200
height=200></applet>
public class SBDemo extends Applet implements
AdjustmentListener,MouseMotionListener{
String
msg="";
Scrollbar
vertSB,horzSB;
public void
init()
{
//int
width=Integer.parseInt(getParameter("width"));
// int
height=Integer.parseInt(getParameter("height"));
vertSB=new
Scrollbar(Scrollbar.VERTICAL,0,1,0,200);
horzSB=new
Scrollbar(Scrollbar.HORIZONTAL,0,1,0,200);
add(vertSB);
add(horzSB);
//register
to receive adjustment events
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void
adjustmentValueChanged(AdjustmentEvent ae)
{
repaint();
}
//Update
scroll bars to reflect mouse dragging.
public void
mouseDragged(MouseEvent me)
{
int
x=me.getX();
int
y=me.getY();
vertSB.setValue(y);
horzSB.setValue(x);
repaint();
}
//Necessary
for MouseMotionListener
public void
mouseMoved(MouseEvent me)
{}
//Display
current value of scroll bars.
public void
paint(Graphics g)
{
msg="Vertical
: "+vertSB.getValue();
msg+="Horizontal
:"+horzSB.getValue();
g.drawString(msg,7,120);
//show
current mouse drag position
g.drawString("*",horzSB.getValue(),vertSB.getValue());
}
}
Using ScrollPanes
We want to scroll some tex t.
We want add a component to a scroll pane.
import java.applet.*;
import java.awt.*;
//<applet code=spane.class width=200 height=200></applet>
public class spane extends Applet
{
ScrollPane
sp;
TextField t1;
public void
init()
{
sp=new
ScrollPane();
t1=new
TextField("Hello from Java!");
sp.add(t1);
add(sp);
}
}
Using the Mouse
------------------
MouseListener Which handles mouse clicks,presses, and
releases as well as instances when the mouse enters a component and then leaves
it,
And MouseMotionListener, which handles mouse
movements and drag operation.
Methods of the MouseListener interface.
void mouseClicked(MouseEvent e)
Called when
the mouse has been clicked on a component.
void mouseEntered(MouseEvent e)
called when
the mouse enters a component
void mousExited(MouseEvent e)
called when
the mouse exits a component.
void mousePressed(MouseEvent e)
called when a
mouse button has been pressed on a component
void mouseRelesed(MouseEvent e)
called when a
mouse button has been released on a component.
Methods of MouseMotionListener interface
void mouseDragged(MouseEvent e)
called when a mouse button is
pressed on a component and then dragged.
void mouseMoved(MouseEvent e)
called when
the mouse button has been moved over a component(with no buttons down)
To get the current location of the mouse from a MouseEvent
object, we can use the getX and getY methods. To determine which button when pressed, we
can use the MouseEvent class’s getModifiers methods and then And the result with
these fields from the InputEvent class:
BUTTON1_MASK
CTRL_MASK
SHIFT_MASK
Ex:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=mouse.class width=200
height=200></applet>
public class mouse extends Applet implements
MouseListener,MouseMotionListener
{
TextField t1;
public void
init(){
t1=new
TextField(30);
add(t1);
addMouseListener(this);
addMouseMotionListener(this);
}
public void
mousePressed(MouseEvent e)
{
if((e.getModifiers()
& InputEvent.BUTTON1_MASK)==InputEvent.BUTTON1_MASK)
{
t1.setText("Left
mouse button down at :"+e.getX()+","+e.getY());
}
else
{
t1.setText("Right
mouse button down at :"+e.getX()+","+e.getY());
}
}
public void
mouseClicked(MouseEvent e)
{
t1.setText("You
clicked the mouse at :"+e.getX()+","+e.getY());
}
public void
mouseReleased(MouseEvent e)
{
t1.setText("The
mouse button went up");
}
public void
mouseEntered(MouseEvent e)
{
t1.setText("The
mouse Entered");
}
public void
mouseExited(MouseEvent e)
{
t1.setText("The
mouse was exited");
}
public void
mouseDragged(MouseEvent e)
{
t1.setText("The
mouse was dragged");
}
public void
mouseMoved(MouseEvent e)
{
t1.setText("The
mouse was moved");
}
}
Creating Windowed Applications
--------------------------------------------
Frame() Constructs
a new instance of Frame that’s initially invisible.
Frame(String titile)
Constructs a
new Frame object that’s invisible, with
the given title.
Ex:
import
java.applet.*;
import
java.awt.*;
import java.awt.event.*;
class AppFrame extends Frame
{
public void
paint(Graphics g)
{
g.drawString("HELLO
FRIENDS",75,100);
}
}
public class App
{
public static
void main(String args[])
{
AppFrame
f=new AppFrame();
f.setSize(200,200);
f.addWindowListener(new
WindowAdapter(){
public
void windowClosing(WindowEvent e)
{
System.exit(0);}
});
f.show();
}
}
Clicking the close button has no
effect at all.
Understanding Layout Managers
==============================
Layout:
---------
To arranging the
AWT components
Layout is set by
the following method
void
setLayout(LayoutManager layoutobject);
Here, layoutObj
is a reference to the desired layout manager.
Types:
------
Flow Layout (Left top right bottom)
Border
Layout (N,E,S,W,C)
Grid Layout (Row & Column manner)
Card Layout
Panel (to group the components)
FlowLayout
=============
FlowLayout is the default layout manager.
FlowLayout()
creates the
default layout, which centers components and leaves five pixels of space
between each component.
FlowLayout(int how)
how each line
is aligned.
valid values
for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout(int how,int horz,int vert)
import
java.awt.*;
import
java.applet.*;
//<applet code=flow.class width=200
height=200></applet>
public class flow extends Applet {
TextField t1,t2,t3;
public void init(){
setLayout(new
FlowLayout(FlowLayout.RIGHT));
t1=new
TextField(10);
t2=new
TextField(10);
t3=new
TextField(10);
add(t1);
add(t2);
add(t3);
}
}
ex:2
import
java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=multi.class width=190
height=200></applet>
public class multi extends Applet implements ActionListener{
TextField
t1,t2,t3;
Label m;
Button b1;
public void
init()
{
setLayout(new
FlowLayout(FlowLayout.RIGHT));
t1=new
TextField(10);
add(t1);
m=new
Label("*");
add(m);
t2=new
TextField(10);
add(t2);
b1=new
Button("=");
add(b1);
b1.addActionListener(this);
t3=new
TextField(10);
add(t3);
}
public void
actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
int
product=Integer.parseInt(t1.getText())*Integer.parseInt(t2.getText());
t3.setText(String.valueOf(product));
}
}
}
import
java.awt.*;
import
java.applet.*;
import java.awt.event.*;
//<applet code="FlowLayoutDemo" width=200
height=200 ></applet>
public class FlowLayoutDemo extends Applet implements
ItemListener{
String
msg="";
Checkbox
c1,c2,c3,c4;
public void
init(){
setLayout(new
FlowLayout(FlowLayout.CENTER));
c1=new
Checkbox("Windows 98",true);
c2=new
Checkbox("Windows NT");
c3=new
Checkbox("Unix");
c4=new
Checkbox("Linux");
add(c1);
add(c2);
add(c3);
add(c4);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
}
public void
itemStateChanged(ItemEvent ie){
repaint();
}
public void
paint(Graphics g)
{
msg="Current
state";
g.drawString(msg,6,80);
msg="Windows
98:"+c1.getState();
g.drawString(msg,6,100);
msg="Windows
NT:"+c2.getState();
g.drawString(msg,6,120);
msg="Unix
:"+c3.getState();
g.drawString(msg,6,140);
msg="Linux:"+c4.getState();
g.drawString(msg,6,160);
}
}
GridLayout
--------------
GridLayout()
GridLayout(int numRows,int numColumns)
GridLayout(int numRows,int numColumns,int horz,int vert)
Ex:
import
java.awt.*;
import
java.awt.event.*;
import java.applet.*;
//<applet code=multi1.class width=200
height=200></applet>
public class multi1 extends Applet implements
ActionListener{
TextField
t1,t2,t3;
Label m;
Button b1;
public void
init()
{
setLayout(new
GridLayout(5,1));
t1=new
TextField(10);
add(t1);
m=new
Label("*",Label.CENTER);
add(m);
t2=new
TextField(10);
add(t2);
b1=new
Button("=");
add(b1);
b1.addActionListener(this);
t3=new
TextField(10);
add(t3);
}
public void
actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
int
product=Integer.parseInt(t1.getText())*Integer.parseInt(t2.getText());
t3.setText(String.valueOf(product));
}
}
}
import
java.applet.*;
import
java.awt.*;
//<applet code=GridLayoutDemo height=200
width=200></applet>
public class GridLayoutDemo extends Applet{
static final
int n=4;
public void
init(){
setLayout(new
GridLayout(n,n));
setFont(new
Font("SansSerif",Font.BOLD,20));
for(int
i=0;i<n;i++){
for(int
j=0;j<n;j++){
int
k=i*n+j;
if(k>0)
add(new
Button(""+k));
}
}
}
}
BorderLayout
---------------
BorderLayout()
BorderLayout(int horz,int vert)
To specify
the horizontal and vertical space left between components in horz and vert,
respectively.
BorderLayout.CENTER
BorderLayout.EAST
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.WEST
void
add(Component combObj, Object region);
compObj is
the component to be added, and region specifies where the component will be
added.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet
code=BorderLayoutDemo width=200 height=200></applet>
public class
BorderLayoutDemo extends Applet{
public
void init()
{
setLayout(new
BorderLayout());
add(new
Button("This is across the top."),BorderLayout.NORTH);
add(new
Label("The footer message might go here."),BorderLayout.SOUTH);
add(new
Button("Rigth"),BorderLayout.EAST);
add(new
Button("Left"),BorderLayout.WEST);
String
val="That's why TextPad is so popular. "+"\nWhether you simply
need a powerful replacement for Notepad,"+"\n a tool for editing your
web pages, or "+"\na programming IDE, TextPad does what you
want"+"\n, the way you would expect.";
add(new
TextArea(val),BorderLayout.CENTER);
}
}
--------------------------------------------------------------------------------
Using Insets
---------------
Insets(int top,int left,int bottom,int right)
The amount of space between the container and its enclosing
window.
Insets getInsets()
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=Inset width=200
height=200></applet>
public class Inset extends Applet{
public void
init()
{
setBackground(Color.green);
setLayout(new
BorderLayout());
add(new
Button("This is across the top."),BorderLayout.NORTH);
add(new
Label("The footer message might go here."),BorderLayout.SOUTH);
add(new
Button("Rigth"),BorderLayout.EAST);
add(new
Button("Left"),BorderLayout.WEST);
String
val="That's why TextPad is so popular. "+"\nWhether you simply
need a powerful replacement for Notepad,"+"\n a tool for editing your
web pages, or "+"\na programming IDE, TextPad does what you
want"+"\n, the way you would expect.";
add(new
TextArea(val),BorderLayout.CENTER);
}
//add insets
public Insets
getInsets()
{
return
new Insets(10,10,10,10);
}
}
--------------
----------------
CardLayout
----------------
The CardLayout class is unique among the other layout
managers in that it stores several different layouts.
CardLayout()
CardLayout(int horz,int vert)
Use of card layout requires a bit more work than the other
layouts.The cards are typically held in
an object of type Panel. This panel must
have CardLayout selected as its layout manager.
adding cards to a panel:
void add(Component panelObj,Object name);
name is a string that specifies the name of the card whose
panel is specified by panelObj.
void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck,String cardName)
The show() method displays the card whose name is
passed in cardName.
import
java.awt.*;
import
java.applet.*;
import java.awt.event.*;
//<applet code=CardLayoutDemo height=100
width=100></applet>
public class CardLayoutDemo extends Applet implements ActionListener,MouseListener{
Checkbox
c1,c2,c3,c4;
Panel p1;
CardLayout
cardLO;
Button b1,b2;
public void
init()
{
b1=new
Button("Windows");
b2=new
Button("Others");
add(b1);
add(b2);
cardLO=new
CardLayout();
p1=new
Panel();
p1.setLayout(cardLO);//set
panel layout to card layout
c1=new
Checkbox("Window 98",true);
c2=new
Checkbox("Window NT");
c3=new
Checkbox("Unix");
c4=new
Checkbox("Linux");
//add
windows check box to a panel
Panel
win=new Panel();
win.add(c1);
win.add(c2);
//add
other OS check boxes to a panel
Panel
other=new Panel();
other.add(c3);
other.add(c4);
//add
panels to card deck panel
p1.add(win,"Windows");
p1.add(other,"Other");
//add
cards to main applet panel
add(p1);
b1.addActionListener(this);
b2.addActionListener(this);
addMouseListener(this);
}
//Cycle
through panels.
public void
mousePressed(MouseEvent me){
cardLO.next(p1);
}
//provide
empty implementations for the other MouseListener methods
public void
mouseClicked(MouseEvent me){}
public void
mouseEntered(MouseEvent me){}
public void
mouseExited(MouseEvent me){}
public void
mouseReleased(MouseEvent me){}
public void
actionPerformed(ActionEvent ae){
if(ae.getSource()==b1)
{
cardLO.show(p1,"Windows");
}
else
{
cardLO.show(p1,"Other");
}
}
}
KeyEvent Class:
---------------
types of
keyEvent:
--------------
KEY_PRESSED
KEY_RELEASED
KEY_TYPED
OTHER KEY
Constants:
--------------------
VK_0 through VK_9
VK_A through VK_Z
VK_ENTER
VK_ESCAPE
VK_CANCEL
VK_UP
VK_DOWN
VK_LEFT
VK_RIGHT
VK_PAGEDOWN
VK_PAGEUP
VK_SHIFT
VK_ALT
VK_CONTROL
VK -Virtual Key
code
independent
of any modifiers such as Ctrl,Alt and shift
Methods:
---------
char getKeyChar();
int getKeyCode();
KeyListener:
--------------
void
keyPressed(KeyEvent ke)
void
keyReleased(KeyEvent ke)
void
keyTyped(KeyEvent ke)
import
java.awt.*;
import
java.awt.event.*;
import java.applet.*;
/*<applet code=SimpleKey width=300
height=100></applet>*/
public class SimpleKey extends Applet implements
KeyListener{
String
msg="";
int
X=20,Y=30;//output coordinates
public void
init(){
addKeyListener(this);
requestFocus();//request
input focus
}
public void
keyPressed(KeyEvent ke){
showStatus("Key
Down");
}
public void
keyReleased(KeyEvent ke){
showStatus("Key
Up");
}
public void
keyTyped(KeyEvent ke){
msg+=ke.getKeyChar();
repaint();
}
//Display
keystrokes.
public void
paint(Graphics g){
g.drawString(msg,X,Y);
}
}
we want to handle the special keys, such as the arrow or
function keys, we need to respond to them within the keyPressed() handler.
Demonstrate some virtual key codes.
import
java.awt.*;
import
java.awt.event.*;
import java.applet.*;
//<applet code=KeyEvents width=300
height=200></applet>
public class KeyEvents extends Applet implements
KeyListener{
String
msg="";
int
x=10,y=20;
public void
init(){
addKeyListener(this);
requestFocus();
}
public void
keyPressed(KeyEvent ke){
showStatus("Key
Down");
int
key=ke.getKeyCode();
switch(key){
case
KeyEvent.VK_F1:
msg+="<F1>";
break;
case
KeyEvent.VK_F2:
msg+="<F2>";
break;
case
KeyEvent.VK_F3:
msg+="<F3>";
break;
case
KeyEvent.VK_PAGE_DOWN:
msg+="<PgDn>";
break;
case
KeyEvent.VK_PAGE_UP:
msg+="<PgUp>";
break;
case
KeyEvent.VK_LEFT:
msg+="<Left
Arrow>";
break;
case
KeyEvent.VK_RIGHT:
msg+="<Right
Arrow>";
break;
}
repaint();
}
public
void keyReleased(KeyEvent ke){
showStatus("Key
Up");
}
public
void keyTyped(KeyEvent ke){
msg+=ke.getKeyChar();
repaint();
}
public
void paint(Graphics g){
g.drawString(msg,x,y);
}
}
Menu Bars and Menu
A menu bar contains one or more Menu objects. Each Menu object contains a list of MenuItem
objects. Each MenuItem object represents
something that can be selected by the user.
Since Menu is a subclass of MenuItem a hierarchy of nested sunmenus can
be created. It is possible to include
checkable menu items.
These are menu options of type CheckboxMenuItem and will
hava a check mark next to them when they are selected.
Constructors of Menu:
--------------------
Menu(); -
creates an empty menu.
Menu(String optionname);
Menu(String optionname,boolean removable);
Here, optionName specifies the name of the menu
selection. If removable is true, the
pop-up menu can be removed and allowed to float free.
Constructors of MenuItem:
--------------------------
MenuItem();
MenuItem(String itemname);
MenuItem(String itemname,MenuShortcut keyAccel);
itemname is the name shown in the menu, and keyAccel is the
menu shortcut for this item.
Menuitem can be disable or enabled by
----------
void setEnabled(boolean enabledflag);
We can determine an item's status by calling isEnabled().
boolean isEnabled()
name of the menuitem can be changed by
-------------------------------
void setLabel(String newname);
String getLabel();
CheckboxMenuItem constructors:
CheckboxMenuItem()
CheckboxMenuItem(String itemName)
CheckboxMenuItem(String itemName,boolean on)
itemName is the name shown in the menu. Checkable items operate as toggles.
In the first two forms, the checkable entry is unchecked. In third form, if on is true, the checkable
entry is initially checked. Otherwise,
it is cleared.
we have create a menu item, we must add the item to a Menu
object by using add().
MenuItem add(MenuItem item)
Menu add(Menu menu);
Each time a menu item is selected, an ActionEvent object is
generated. Each time a check box menu
item is checked or unchecked, an ItemEvent object is generated.
We must implement the ActionListener and ItemListener
interfaces in order to handle these menu events.
import
java.awt.event.*;
import
java.awt.*;
import java.applet.*;
//<applet code=MenuDemo width=200
height=200></applet>
class win1 extends Frame implements
ActionListener,ItemListener
{
MenuBar mb;
MenuItem
f1,f2,f3,f4,f5,e1,e2,e3,e4;
Menu
file,edit;
CheckboxMenuItem
debug,test;
String
msg="";
win1(String
tit)
{
super(tit);
//setLayout(new
GridLayout(1,1));
setSize(400,400);
mb=new
MenuBar();
file=new
Menu("File");
f1=new
MenuItem("New");
f2=new
MenuItem("Open");
f3=new
MenuItem("Close");
f4=new
MenuItem("-");
f5=new
MenuItem("Quit");
file.add(f1);
file.add(f2);
file.add(f3);
file.add(f4);
file.add(f5);
mb.add(file);
edit=new
Menu("Edit");
e1=new
MenuItem("Copy");
e2=new
MenuItem("Cut");
e3=new
MenuItem("Paste");
e4=new
MenuItem("-");
edit.add(e1);
edit.add(e2);
edit.add(e3);
edit.add(e4);
Menu
sub=new Menu("Special");
MenuItem
s1,s2,s3;
s1=new
MenuItem("First");
s2=new
MenuItem("Second");
s3=new
MenuItem("Third");
sub.add(s1);
sub.add(s2);
sub.add(s3);
edit.add(sub);
//these
are checkable menu items
debug=new
CheckboxMenuItem("Debug");
test=new
CheckboxMenuItem("Testing");
edit.add(debug);
edit.add(test);
f1.addActionListener(this);
f2.addActionListener(this);
f3.addActionListener(this);
f4.addActionListener(this);
f5.addActionListener(this);
e1.addActionListener(this);
e2.addActionListener(this);
e3.addActionListener(this);
e4.addActionListener(this);
s1.addActionListener(this);
s2.addActionListener(this);
s3.addActionListener(this);
debug.addItemListener(this);
test.addItemListener(this);
mb.add(edit);
setMenuBar(mb);
}
public void
itemStateChanged(ItemEvent ie){
repaint();
}
public void
actionPerformed(ActionEvent ae){
String
msg="You Selected";
String
arg=(String)ae.getActionCommand();
if(arg.equals("New"))
msg+="New";
this.msg=msg;
if(arg.equals("Open"))
msg+="Open";
this.msg=msg;
repaint();
}
public void
paint(Graphics g)
{
g.drawString(msg,10,200);
if(debug.getState())
g.drawString("Debug
is on.",10,220);
else
g.drawString("Debut
is off.",10,220);
if(test.getState())
g.drawString("Testing
is on.",10,240);
else
g.drawString("Testing
is off",10,240);
}
}
public class MenuDemo extends Applet implements
ActionListener
{
win1 w;
Button b1,b2;
public void
init()
{
b1=new
Button("Show window");
b2=new
Button("Hidewindow");
w=new
win1("My Own Window");
add(b1);
add(b2);
w.setSize(300,200);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void
actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
w.setVisible(true);
else
if(ae.getSource()==b2)
w.setVisible(false);
}
}
================================================
------------------
void show(Componenet
origin,int x,int y)
shows the
pop-up menu at the x,y position.
Awtprg.popmenu
import
java.awt.*;
import
java.awt.event.*;
import java.applet.*;
//<applet code=popmenu.class width=200
height=200></applet>
public class popmenu extends Applet implements
ActionListener,MouseListener
{
Label l1;
PopupMenu
pop;
MenuItem
red,green,blue;
public void
init(){
pop=new
PopupMenu("Menu");
red=new
MenuItem("RED");
red.addActionListener(this);
green=new
MenuItem("GREEN");
green.addActionListener(this);
blue=new
MenuItem("BLUE");
blue.addActionListener(this);
pop.add(red);
pop.add(green);
pop.addSeparator();
pop.add(blue);
add(pop);
l1=new
Label("Hello Friends");
add(l1);
addMouseListener(this);
}
public void
mousePressed(MouseEvent e)
{
if(e.getModifiers()!=0){
pop.show(this,e.getX(),e.getY());
}
}
public void
mouseClicked(MouseEvent e){ }
public void
mouseReleased(MouseEvent e){}
public void
mouseEntered(MouseEvent e) {}
public void
mouseExited(MouseEvent e){}
public void
actionPerformed(ActionEvent ae)
{
if(ae.getSource()==red)
{
l1.setBackground(Color.red);
l1.setText("You chose red");
}
else
if(ae.getSource()==green)
{
l1.setBackground(Color.green);
l1.setText("You
chose green");
}
else
if(ae.getSource()==blue){
l1.setBackground(Color.blue);
l1.setText("You
chose blue");
}
}
}
No comments:
Post a Comment