AWT Tutorial (1)
AWT Tutorial (1)
MADHAVI 1
AWT
Components
All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component as shown in
above diagram. In order to place every component in a particular position on a
screen, we need to add them to a container.
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.
Types of containers:
There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog
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. We need to create an
instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is
generic container for holding the components. It can have other components like
button, text field etc. An instance of Panel class creates a container, in which we
can add components.
Frame
The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame is
most widely used container while developing an AWT application.
MADHAVI 2
AWT
MADHAVI 3
AWT
MADHAVI 4
AWT
MADHAVI 5
AWT
{
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome to ITTEAMWORK");
}
});
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT Label
The object of the Label class is a component for placing text in a container. It is
used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed.
To create a label, we need to create the object of Label class.
AWT Label Class Declaration
public class Label extends Component implements Accessible
AWT Label Fields
The java.awt.Component class has following fields:
static int LEFT: It specifies that the label should be left justified.
static int RIGHT: It specifies that the label should be right justified.
static int CENTER: It specifies that the label should be placed in center.
MADHAVI 6
AWT
MADHAVI 7
AWT
f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT Label Example 2
import java.awt.*;
import java.awt.event.*;
public class LabelEx2 extends Frame implements ActionListener
{
TextField tf;
Label l;
Button b;
LabelEx2()
{
tf=new TextField();
tf.setBounds(50,50,150,20);
l=new Label();
l.setBounds(50,100,250,20);
b=new Button("Find IP");
b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b);
add(l);
add(tf);
setSize(400,400);
MADHAVI 8
AWT
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try
{
String host=tf.getText();
String
ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
public static void main(String []args)
{
new LabelEx2();
}
}
Java AWT TextField
The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further
inherits Component class.
When we enter a key in the text field (like key pressed, key released or key
typed), the event is sent to TextField. Then the KeyEvent is passed to the
registered KeyListener. It can also be done using ActionEvent; if the
MADHAVI 9
AWT
ActionEvent is enabled on the text field, then the ActionEvent may be fired by
pressing return key. The event is handled by the ActionListener interface.
AWT TextField Class Declaration
public class TextField extends TextComponent
TextField Class constructors
Constructor Description
TextField() It constructs a new text field
component.
TextField(String text) It constructs a new text field
initialized with the given string text to
be displayed.
TextField(int columns) It constructs a new textfield (empty)
with given number of columns.
TextField(String text, int columns) It constructs a new text field with the
given text and given number of
columns (width).
TextField Class Methods
Method Description
void addNotify() It creates the peer of text field.
boolean echoCharIsSet() It tells whether text field has character
set for echoing or not.
void It adds the specified action listener to
addActionListener(ActionListener l) receive action events from the text
field.
ActionListener[] getActionListeners() It returns array of all action listeners
registered on text field.
AccessibleContext It fetches the accessible context
getAccessibleContext() related to the text field.
int getColumns() It fetches the number of columns in
text field.
char getEchoChar() It fetches the character that is used for
echoing.
Dimension getMinimumSize() It fetches the minimum dimensions
for the text field.
Dimension getMinimumSize(int It fetches the minimum dimensions
columns) for the text field with specified
number of columns.
1
MADHAVI
0
AWT
1
MADHAVI
1
AWT
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT TextField Example 2
import java.awt.*;
import java.awt.event.*;
public class TextFieldEx2 extends Frame implements ActionListener
{
TextField t1,t2,t3;
Button b1,b2;
TextFieldEx2()
{
t1=new TextField();
t1.setBounds(50,100,200,30);
t2=new TextField();
t2.setBounds(50,150,200,30);
t3=new TextField();
t3.setBounds(50,200,200,30);
t3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,250,50,50);
b2=new Button("-");
b2.setBounds(120,250,50,50);
b1.addActionListener(this);
1
MADHAVI
2
AWT
b2.addActionListener(this);
add(t1);
add(t2);
add(t3);
add(b1);
add(b2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String s1=t1.getText();
String s2=t2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1)
{
c=a+b;
}
else if(e.getSource()==b2)
{
c=a-b;
}
String result=String.valueOf(c);
t3.setText(result);
1
MADHAVI
3
AWT
}
public static void main(String []args)
{
new TextFieldEx2();
}}
Java AWT TextArea
The object of a TextArea class is a multiline region that displays text. It allows
the editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the
text area becomes larger than the viewable area, the scroll bar appears
automatically which helps us to scroll the text up and down, or right and left.
AWT TextArea Class Declaration
public class TextArea extends TextComponent
Fields of TextArea Class
The fields of java.awt.TextArea class are as follows:
static int SCROLLBARS_BOTH - It creates and displays both horizontal and
vertical scrollbars.
static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays
only the horizontal scrollbar.
static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only
the vertical scrollbar.
static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in
the text area.
Class constructors:
Constructor Description
TextArea() It constructs a new and empty text
area with no text in it.
TextArea (int row, int column) It constructs a new text area with
specified number of rows and
columns and empty string as text.
1
MADHAVI
4
AWT
1
MADHAVI
6
AWT
Label l1,l2;
TextArea area;
Button b;
TextAreaEx2()
{
l1=new Label();
l1.setBounds(50,50,100,30);
l2=new Label();
l2.setBounds(160,50,100,30);
area=new TextArea();
area.setBounds(20,100,300,300);
b=new Button("Count Words");
b.setBounds(100,400,100,30);
b.addActionListener(this);
add(l1);
add(l2);
add(area);
add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
1
MADHAVI
7
AWT
l2.setText("Characters: "+text.length());
}
public static void main(String []args)
{
new TextAreaEx2();
}
}
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on
(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off"
or from "off" to "on".
AWT Checkbox Class Declaration
public class Checkbox extends Component implements ItemSelectable,
Accessible
Checkbox Class Constructors
Constructor Description
Checkbox() It constructs a checkbox with no
string as the label.
Checkbox(String label) It constructs a checkbox with the
given label.
Checkbox(String label, boolean state) It constructs a checkbox with the
given label and sets the given state.
Checkbox(String label, boolean state, It constructs a checkbox with the
CheckboxGroup group) given label, set the given state in the
specified checkbox group.
Checkbox(String label, It constructs a checkbox with the
CheckboxGroup group, boolean state) given label, in the given checkbox
group and set to the specified state.
Checkbox Class Methods
Method name Description
void addItemListener(ItemListener It adds the given item listener to get
IL) the item events from the checkbox.
AccessibleContext It fetches the accessible context of
getAccessibleContext() checkbox.
1
MADHAVI
8
AWT
cb1.setBounds(100,100,50,50);
Checkbox cb2=new Checkbox("Java");
cb2.setBounds(100,150,50,50);
f.add(cb1);
f.add(cb2);
f.add(l);
cb1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
l.setText("C++ Checkbox:
"+(e.getStateChange()==1?"checked":"unchecked"));
}
});
cb2.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
l.setText("Java Checkbox:
"+(e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String []args)
2
MADHAVI
1
AWT
{
new CheckboxEx2();
}
}
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox.
At a time only one check box button is allowed to be in "on" state and
remaining check box button in "off" state. It inherits the object class.
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no
special control for creating radio buttons in AWT.
AWT CheckboxGroup Class Declaration
public class CheckboxGroup extends Object implements Serializable
Java AWT CheckboxGroup Example1
import java.awt.*;
public class CheckboxGroupEx
{
CheckboxGroupEx()
{
Frame f=new Frame("CheckboxGroup Example");
CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new Checkbox("C++",cbg,false);
cb1.setBounds(100,100,50,50);
Checkbox cb2=new Checkbox("Java",cbg,false);
cb2.setBounds(100,150,50,50);
f.add(cb1);
f.add(cb2);
f.setSize(400,400);
f.setLayout(null);
2
MADHAVI
2
AWT
f.setVisible(true);
}
public static void main(String []args)
{
new CheckboxGroupEx();
}
}
Java AWT CheckboxGroup Example 2
import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupEx2
{
CheckboxGroupEx2()
{
Frame f=new Frame("CheckboxGroup Example");
final Label l=new Label();
l.setAlignment(Label.CENTER);
l.setSize(400,100);
CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new Checkbox("C++",cbg,false);
cb1.setBounds(100,100,50,50);
Checkbox cb2=new Checkbox("Java",cbg,false);
cb2.setBounds(100,150,50,50);
f.add(cb1);
f.add(cb2);
f.add(l);
cb1.addItemListener(new ItemListener()
2
MADHAVI
3
AWT
{
public void itemStateChanged(ItemEvent e)
{
l.setText("C++ Checkbox: checked");
}
});
cb2.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
l.setText("Java Checkbox: checked");
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String []args)
{
new CheckboxGroupEx2();
}
}
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits Component class.
AWT Choice Class Declaration
public class Choice extends Component implements ItemSelectable, Accessible
2
MADHAVI
4
AWT
2
MADHAVI
6
AWT
}
public static void main(String []args)
{
new ChoiceEx();
}
}
Java AWT Choice Example2
import java.awt.*;
import java.awt.event.*;
public class ChoiceEx2 extends Frame
{
ChoiceEx2()
{
final Label l=new Label();
l.setAlignment(Label.CENTER);
l.setSize(400,100);
Button b=new Button("Show");
b.setBounds(200,100,50,20);
final Choice c=new Choice();
c.setBounds(100,100,75,75);
c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
add(c);
add(l);
2
MADHAVI
7
AWT
add(b);
setSize(500,500);
setLayout(null);
setVisible(true);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data="Programming Language Selected:
"+c.getItem(c.getSelectedIndex());
l.setText(data);
}
});
}
public static void main(String []args)
{
new ChoiceEx2();
}
}
Java AWT List
The object of List class represents a list of text items. With the help of the List
class, user can choose either one item or multiple items. It inherits the
Component class.
AWT List class Declaration
public class List extends Component implements ItemSelectable, Accessible
2
MADHAVI
8
AWT
3
MADHAVI
0
AWT
add(l2);
setSize(450,450);
setLayout(null);
setVisible(true);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data="Programming Language Selected:
"+l1.getItem(l1.getSelectedIndex());
data +=" ,FrameworkSelected: ";
for(String frame:l2.getSelectedItems())
{
data+=frame +"";
}
label.setText(data);
}
});
}
public static void main(String []args)
{
new ListEx2();
}
}
Java AWT Canvas
The Canvas class controls and represents a blank rectangular area where the
application can draw or trap input events from the user. It inherits the
Component class.
3
MADHAVI
3
AWT
f.setVisible(true);
}
public static void main(String args[])
{
new CanvasExample();
}
}
class MyCanvas extends Canvas
{
public MyCanvas() {
setBackground (Color.cyan);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and
columns.
It can be added to top-level container like Frame or a component like Panel. The
Scrollbar class extends the Component class.
AWT Scrollbar Class Declaration
public class Scrollbar extends Component implements Adjustable, Accessible
3
MADHAVI
5
AWT
3
MADHAVI
6
AWT
3
MADHAVI
7
AWT
{
ScrollbarEx()
{
Scrollbar s=new Scrollbar();
s.setBounds(100,100,50,100);
add(s);
setSize(500,500);
setLayout(null);
setVisible(true);
}
public static void main(String []args)
{
new ScrollbarEx();
}
}
Java AWT Scrollbar Example 2
import java.awt.*;
import java.awt.event.*;
public class ScrollbarEx2 extends Frame
{
ScrollbarEx2()
{
final Label l=new Label();
l.setAlignment(Label.CENTER);
l.setSize(400,100);
final Scrollbar s=new Scrollbar();
s.setBounds(100,100,50,100);
3
MADHAVI
8
AWT
add(s);
add(l);
setSize(500,500);
setLayout(null);
setVisible(true);
s.addAdjustmentListener(new AdjustmentListener(){
public void adjustmentValueChanged(AdjustmentEvent e)
{
l.setText("Vertical Scrollbar value is: "+s.getValue());
}
});
}
public static void main(String []args)
{
new ScrollbarEx2();
}
}
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The
items used in a menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on
the menu bar. It inherits the MenuItem class.
AWT MenuItem class declaration
public class MenuItem extends MenuComponent implements Accessible
Java AWT MenuItem and Menu Example
import java.awt.*;
class MenuExample
3
MADHAVI
9
AWT
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
4
MADHAVI
0
AWT
}
Java AWT PopupMenu
PopupMenu can be dynamically popped up at specific position within a
component. It inherits the Menu class.
Example:
import java.awt.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final Frame f= new Frame("PopupMenu Example");
final PopupMenu popupmenu = new PopupMenu("Edit");
MenuItem cut = new MenuItem("Cut");
cut.setActionCommand("Cut");
MenuItem copy = new MenuItem("Copy");
copy.setActionCommand("Copy");
MenuItem paste = new MenuItem("Paste");
paste.setActionCommand("Paste");
popupmenu.add(cut);
popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
f.add(popupmenu);
4
MADHAVI
1
AWT
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample();
}
}
Java AWT Panel
The Panel is a simplest container class. It provides space in which an
application can attach any other component. It inherits the Container class.
It doesn't have title bar.
Example:
import java.awt.*;
public class PanelExample
{
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.cyan);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.pink);
Button b2=new Button("Button 2");
4
MADHAVI
2
AWT
b2.setBounds(100,100,80,30);
b2.setBackground(Color.blue);
panel.add(b1);
panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used
to take some form of input from the user. It inherits the Window class.
Unlike Frame, it doesn't have maximize and minimize buttons.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and
minimize buttons but Dialog doesn't have.
Example:
import java.awt.*;
import java.awt.event.*;
public class DialogExample
{
private static Dialog d;
4
MADHAVI
3
AWT
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Java AWT Toolkit
Toolkit class is the abstract superclass of every implementation in the Abstract
Window Toolkit. Subclasses of Toolkit are used to bind various components. It
inherits Object class.
4
MADHAVI
4
AWT
Example1:
import java.awt.*;
public class ToolkitExample
{
public static void main(String[] args)
{
Toolkit t = Toolkit.getDefaultToolkit();
System.out.println("Screen resolution = " + t.getScreenResolution());
Dimension d = t.getScreenSize();
System.out.println("Screen width = " + d.width);
System.out.println("Screen height = " + d.height);
}
}
Example 2: Beep()
import java.awt.*;
import java.awt.event.*;
public class ToolkitExample2
{
public static void main(String[] args)
{
Frame f=new Frame("ToolkitExample2");
Button b=new Button("beep");
b.setBounds(50,100,60,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
4
MADHAVI
5
AWT
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Toolkit.getDefaultToolkit().beep();
}
});
}
}
Example 3:Icon Image
import java.awt.*;
class ToolkitExample3
{
ToolkitExample3()
{
Frame f=new Frame();
Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.jpg");
f.setIconImage(icon);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String args[])
{
new ToolkitExample3();
}
}
4
MADHAVI
6
AWT
4
MADHAVI
7
AWT
t.setBounds(50,50,150,20);
Button b=new Button("Chick Here");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
t.setText("Welcome to Itteamwork.");
}
});
f.add(b);
f.add(t);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It
is notified against MouseEvent. The MouseListener interface is found in
java.awt.event package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);
4
MADHAVI
8
AWT
MouseListenerExample1 in AWT.
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
4
MADHAVI
9
AWT
5
MADHAVI
0
AWT
5
MADHAVI
1
AWT
l=new Label();
l.setBounds(20,40,100,20);
add(l);
addMouseMotionListener(this);
setSize(500,500);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e)
{
l.setText("X="+e.getX()+",Y="+e.getY());
Graphics g=getGraphics();
g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e)
{
l.setText("X="+e.getX()+",Y="+e.getY());
}
public static void main(String[] args)
{
new MouseMotionListenerExample();
}
}
5
MADHAVI
2
AWT
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: "+
(e.getStateChange()==1?"checked":"unchecked"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "+
(e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
new ItemListenerExample();
}
}
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is
notified against KeyEvent. The KeyListener interface is found in java.awt.event
package, and it has three methods.
Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:
public interface KeyListener extends EventListener
5
MADHAVI
4
AWT
5
MADHAVI
5
AWT
setVisible (true);
}
public void keyPressed (KeyEvent e)
{
l.setText ("Key Pressed");
}
public void keyReleased (KeyEvent e)
{
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters: "+text.length());
}
public void keyTyped (KeyEvent e)
{
l.setText ("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample();
}
}
KeyListenerExample 2 (Count Words & Characters)
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits Frame class and implements KeyListener interface
public class KeyListenerExample2 extends Frame implements KeyListener {
// object of Label and TextArea
5
MADHAVI
6
AWT
Label l;
TextArea area;
// class constructor
KeyListenerExample2() {
// creating the label
l = new Label();
// setting the location of label
l.setBounds (20, 50, 200, 20);
// creating the text area
area = new TextArea();
// setting location of text area
area.setBounds (20, 80, 300, 300);
// adding KeyListener to the text area
area.addKeyListener(this);
// adding label and text area to frame
add(l);
add(area);
// setting size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// even if we do not define the interface methods, we need to override them
public void keyPressed(KeyEvent e) {}
// overriding the keyReleased() method of KeyListener interface
public void keyReleased (KeyEvent e) {
// defining a string which is fetched by the getText() method of TextArea class
5
MADHAVI
7
AWT
5
MADHAVI
8
AWT
}
public void windowActivated (WindowEvent arg0)
{
System.out.println("activated");
}
public void windowClosed (WindowEvent arg0)
{
System.out.println("closed");
}
public void windowClosing (WindowEvent arg0)
{
System.out.println("closing");
dispose();
}
public void windowDeactivated (WindowEvent arg0)
{
System.out.println("deactivated");
}
public void windowDeiconified (WindowEvent arg0)
{
System.out.println("deiconified");
}
public void windowIconified (WindowEvent arg0)
{
System.out.println("iconified");
}
public void windowOpened (WindowEvent arg0)
6
MADHAVI
0
AWT
{
System.out.println("opened");
}
}
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If
you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves code.
Pros of using Adapter classes:
It assists the unrelated classes to work combinedly.
It provides ways to use classes in different ways.
It increases the transparency of classes.
It provides a way to include related patterns in the class.
It provides a pluggable kit for developing an application.
It increases the reusability of the class.
The adapter classes are found in java.awt.event, java.awt.dnd and
javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given
below.
java.awt.event Adapter classes
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
java.awt.dnd Adapter classes
Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
6
MADHAVI
1
AWT
6
MADHAVI
2
AWT
}
// main method
public static void main(String[] args) {
new AdapterExample();
}
}
Java MouseAdapter Example
In the following example, we are implementing the MouseAdapter class. The
MouseListener interface is added into the frame to listen the mouse event in the
frame.
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseAdapter class
public class MouseAdapterExample extends MouseAdapter {
// object of Frame class
Frame f;
// class constructor
MouseAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Adapter");
// adding MouseListener to the Frame
f.addMouseListener(this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
6
MADHAVI
3
AWT
}
// overriding the mouseClicked() method of the MouseAdapter class
public void mouseClicked (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object using
getGraphics() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.BLUE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 30, 30);
}
// main method
public static void main(String[] args) {
new MouseAdapterExample();
}
}
Java MouseMotionAdapter Example
In the following example, we are implementing the MouseMotionAdapter class
and its different methods to listen to the mouse motion events in the Frame
window.
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseMotionAdapter class
public class MouseMotionAdapterExample extends MouseMotionAdapter {
// object of Frame class
Frame f;
// class constructor
6
MADHAVI
4
AWT
MouseMotionAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Motion Adapter");
// adding MouseMotionListener to the Frame
f.addMouseMotionListener (this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
// overriding the mouseDragged() method
public void mouseDragged (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object using
getGraphics() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.ORANGE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 20, 20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
Java KeyAdapter Example
In the following example, we are implementing the KeyAdapter class and its
method.
6
MADHAVI
5
AWT
6
MADHAVI
7
AWT
6
MADHAVI
8
AWT
setVisible (true);
}
// main method
public static void main (String[] args) {
new WindowExample();
}
Close AWT Window Example 2: extending WindowAdapter
In the following example, we are implementing the window closing
functionality using the WindowAdapter class.
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the WindowAdapter class
public class AdapterExample extends WindowAdapter {
// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating the frame
f = new Frame();
// adding WindowListener to the frame
f.addWindowListener (this);
// setting the size, layout and visibility of frame
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
6
MADHAVI
9
AWT
7
MADHAVI
0
AWT
// main method
public static void main(String[] args) {
new WindowExample();
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
dispose();
}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent arg0) {}
}
7
MADHAVI
1