Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

INTRODUCTION TO AWT

Java AWT (Abstract Window Toolkit) is an API(Application Programming Interface) to develop GUI or window-based applications in java.

AWT CLASSES :

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

The hierarchy of Java AWT classes are given below.

Container

The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends
Container class are known as container such as Frame, Dialog and Panel.

Window

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

Panel

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

Frame

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

Education4Fun.com
Graphical User Interface

 Graphical User Interface (GUI) offers user interaction via some graphical components. For example our underlying
Operating System also offers GUI via window,frame,Panel, Button, Textfield, TextArea, Listbox, Combobox, Label,
Checkbox etc.

Advantages of GUI over CUI


 GUI provides graphical icons to interact while the CUI (Character User Interface) offers the simple text-based
interfaces.

 GUI makes the application more entertaining and interesting on the other hand CUI does not.

 GUI offers click and execute environment while in CUI every time we have to enter the command for a task.

Working with Graphics

The AWT supports a rich assortment of graphics methods.All graphics are drawn relative to window.This can be a main window of an applet,a
child window of an applet ,or stand alone application of window.The origin of each window is at the top-left corner and is 0,0.

A graphics context is encapsulated by the Graphics class and is obtained in two ways:

• It is passed to a method, such as paint( ) or update( ), as an argument.

• It is returned by the getGraphics( ) method of Component.

Commonly used methods of Graphics class:


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

Example :

import java.applet.Applet;

import java.awt.*;

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

public class GraphicsDemo extends Applet{

public void paint(Graphics g){

setBackground(Color.black);

Education4Fun.com
g.setColor(Color.green);

g.drawString("Hello World",50, 50);

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

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

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

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

g.setColor(Color.pink);

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

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

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

OUTPUT:

EVENT HANDLING

EVENT :

Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user
interaction with the graphical user interface components.

Types of Event

Foreground Events - Those events which require the direct interaction of user. For example, clicking on a button, moving the mouse,
entering a character through keyboard,selecting an item from list, scrolling the page etc.

Background Events - Those events that require the interaction of end user are known as background events. Operating system
interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code
which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events.

Education4Fun.com
TWO EVENT HANDLING MECHANISMS:

The working of an event-driven program is governed by its underlying event-handling model. Till now two models have been introduced in Java
for receiving and processing events.They are :

Java 1.0 Event Model

The Java 1.0 Event model for event processing was based on the concept of containment. In this approach, when a user-initiated event is
generated it is first sent to the component in which the event has occurred. But in case the event is not handled at this component, it is
automatically propagated to the container of that component. This process is continued until the event is processed or it reaches the root of the
containment hierarchy.

Delegation Event Model

The advanced versions of Java ruled out the limitations of Java 1.0 event model. This model defines the standard mechanism to generate and
handle the events. The Delegation Event Model has the following key participants namely Source and Listener.

A source generates an event and sends it to one or more listeners. On receiving the event, listener processes the event and returns it.

• Event source: An event source is an object that generates a particular kind of event. An event is generated when the internal state of
the event source is changed. A source may generate more than one type of event. Every source must register a list of listeners that are interested
to receive the notifications regarding the type of event. Event source provides methods to add or remove listeners.

The general form of method to register (add) a listener is:

public void addTypeListener(TypeListener eventlistener)

Similarly, the general form of method to unregister (remove) a listener is:

public void removeTypeListener(TypeListener eventlistener)

where,Type is the name of the event

eventlistener is a reference to the event listener

Education4Fun.com
• Event listener: An event listener is an object which receives notification when an es about specific types of events. The role of
event listener is to receive these notifications and process them.

For example, as shown in Figure, when the mouse is clicked on Button, an event is generated. If the Button has a registered listener

to handle the event, this event is sent to Button, processed and the output is returned to the user. However, if it has no registered

listener the event will not be propagated upwards to Panel or Frame.

Steps to handle events:

1. Implement appropriate interface in the class.


2. Register the component with the listener.

Example program:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*< applet code="Test" width=300, height=100 > */

public class Test extends Applet implements KeyListener

String msg="";

public void init()

addKeyListener(this);

public void keyPressed(KeyEvent k)

showStatus("KeyPressed");

public void keyReleased(KeyEvent k)

Education4Fun.com
showStatus("KeyRealesed");

public void keyTyped(KeyEvent k)

msg = msg+k.getKeyChar();

repaint();

public void paint(Graphics g)

g.drawString(msg, 20, 40);

EVENT CLASSES:
The Event classes represent the event. Java provides us various Event classes

Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu-item is selected, list-item is double clicked ActionListener

MouseEvent generated when mouse is dragged, moved,clicked,pressed or released and also MouseListener
when it enters or exit a component

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener

MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

WindowEvent generated when window is activated, deactivated, deiconified, iconified, opened or WindowListener
closed

ComponentEvent generated when component is hidden, moved, resized or set visible ComponentEventListener

ContainerEvent generated when component is added or removed from container ContainerListener

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or loses keyboard focus FocusListener

Education4Fun.com
SOURCES OF EVENTS:

EventListener Interfaces

An event listener registers with an event source to receive notifications about the events of a particular type.
Various event listener interfaces defined in the java.awt.event package are given below :

Interface Description
Defines the actionPerformed() method
ActionListener
to receive and process action events.
Defines five methods to receive mouse
events, such as when a mouse is
MouseListener
clicked, pressed, released, enters, or
exits a component
Defines two methods to receive
MouseMotionListener events, such as when a mouse is
dragged or moved.
Defines the adjustmentValueChanged()
AdjustmentListner method to receive and process the
adjustment events.
Defines the textValueChanged()
TextListener method to receive and process an event when the text
value changes.
Defines seven window methods to
WindowListener
receive events.
Defines the itemStateChanged()
ItemListener method when an item has been
selected or deselected by the user.

Education4Fun.com
AWT CONTROL FUNDAMENTALS :

Every AWT controls inherits properties from Component class.

Sr. Control & Description


No.

1 Label

A Label object is a component for placing text in a container.

2 Button

This class creates a labeled button.

3 Check Box

A check box is a graphical component that can be in either


an on(true) or off (false) state.

4 Check Box Group

The CheckboxGroup class is used to group the set of checkbox.

5 List

The List component presents the user with a scrolling list of text
items.

6 Text Field

A TextField object is a text component that allows for the editing of a


single line of text.

7 Text Area

A TextArea object is a text component that allows for the editing of a


multiple lines of text.

8 Choice

Education4Fun.com
A Choice control is used to show pop up menu of choices. Selected
choice is shown on the top of the menu.

9 Canvas

A Canvas control represents a rectangular area where application


can draw something or can receive inputs created by user.

10 Image

An Image control is superclass for all image classes representing


graphical images.

11 Scroll Bar

A Scrollbar control represents a scroll bar component in order to


enable user to select from range of values.

12 Dialog

A Dialog control represents a top-level window with a title and a


border used to take some form of input from the user.

13 File Dialog

A FileDialog control represents a dialog window from which the user


can select a file.

These controls are subclasses of Component.

Adding and Removing Controls

In order to include a control in a window, we must add it to the window. So, we must first create an instance of the desired control and then add
it to a window by calling add( ), which is defined by Container. The add( ) method has several forms.Mostly used form is :
Component add(Component compObj)
Here, compObj is an instance of the control that we want to add.

Sometimes we will want to remove a control from a window when the control is no longer needed. For doing this, call remove( ). This method is
also defined by Container. It has this general form:
void remove(Component obj)
Here, obj is a reference to the control that we want to remove. We can remove all controls by calling removeAll( ).

Responding to Controls

Except for labels, which are passive controls, all controls generate events when they are accessed by the user. For example, when the user clicks
on a push button, an event is sent that identifies the push button. In general, our program simply implements the appropriate interface and then
registers an event listener for each control that we need to monitor.

Education4Fun.com
 JAVA AWT LABEL

The easiest control to use is a label. A label is an object of type Label, and it contains a string, which it displays. Labels are passive controls that
do not support any interaction with the user. Label defines the following constructors:

1 Label()

Constructs an empty label.

2 Label(String text)

Constructs a new label with the specified string of text, left


justified.

3 Label(String text, int alignment)

Constructs a new label that presents the specified string of text


with the specified alignment.

Alignment is of 3 types i.e. Label.LEFT, Label.RIGHT, or


Label.CENTER

AWT Label Class Declaration


1. public class Label extends Component implements Accessible

Java Label Example


1. import java.awt.*;
2. class LabelExample{
3. public static void main(String args[]){
4. Frame f= new Frame("Label Example");
5. Label l1,l2;
6. l1=new Label("First Label.");
7. l1.setBounds(50,100, 100,30);
8. l2=new Label("Second Label.");
9. l2.setBounds(50,150, 100,30);
10. f.add(l1); f.add(l2);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
14. }
15. }

Output:

Education4Fun.com
 Java AWT Button
The button class is used to create a labeled button that has platform independent implementation. The application result in some
action when the button is pushed.

AWT Button Class declaration


1. public class Button extends Component implements Accessible

Java AWT Button Example


1. import java.awt.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. Frame f=new Frame("Button Example");
5. Button b=new Button("Click Here");
6. b.setBounds(50,100,80,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }

Output:

 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


1. public class Checkbox extends Component implements ItemSelectable, Accessible

Education4Fun.com
Java AWT Checkbox Example
1. import java.awt.*;
2. public class CheckboxExample
3. {
4. CheckboxExample(){
5. Frame f= new Frame("Checkbox Example");
6. Checkbox checkbox1 = new Checkbox("C++");
7. checkbox1.setBounds(100,100, 50,50);
8. Checkbox checkbox2 = new Checkbox("Java", true);
9. checkbox2.setBounds(100,150, 50,50);
10. f.add(checkbox1);
11. f.add(checkbox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckboxExample();
19. }
20. }

Output:

 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.

AWT CheckboxGroup Class Declaration


1. public class CheckboxGroup extends Object implements Serializable

Java AWT CheckboxGroup Example


1. import java.awt.*;
2. public class CheckboxGroupExample
3. {
4. CheckboxGroupExample(){
5. Frame f= new Frame("CheckboxGroup Example");
6. CheckboxGroup cbg = new CheckboxGroup();
7. Checkbox checkBox1 = new Checkbox("C++", cbg, false);
8. checkBox1.setBounds(100,100, 50,50);
9. Checkbox checkBox2 = new Checkbox("Java", cbg, true);
10. checkBox2.setBounds(100,150, 50,50);
11. f.add(checkBox1);
12. f.add(checkBox2);
13. f.setSize(400,400);
14. f.setLayout(null);

Education4Fun.com
15. f.setVisible(true);
16. }
17. public static void main(String args[])
18. {
19. new CheckboxGroupExample();
20. }
21. }

Output:

 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


1. public class Choice extends Component implements ItemSelectable, Accessible

Java AWT Choice Example


1. import java.awt.*;
2. public class ChoiceExample
3. {
4. ChoiceExample(){
5. Frame f= new Frame();
6. Choice c=new Choice();
7. c.setBounds(100,100, 75,75);
8. c.add("Item 1");
9. c.add("Item 2");
10. c.add("Item 3");
11. c.add("Item 4");
12. c.add("Item 5");
13. f.add(c);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ChoiceExample();
21. }
22. }

Output:

Education4Fun.com
 Java AWT List
The object of List class represents a list of text items. By the help of list, user can choose either one item or multiple items. It
inherits Component class.

AWT List class Declaration


1. public class List extends Component implements ItemSelectable, Accessible

Java AWT List Example


1. import java.awt.*;
2. public class ListExample
3. {
4. ListExample(){
5. Frame f= new Frame();
6. List l1=new List(5);
7. l1.setBounds(100,100, 75,75);
8. l1.add("Item 1");
9. l1.add("Item 2");
10. l1.add("Item 3");
11. l1.add("Item 4");
12. l1.add("Item 5");
13. f.add(l1);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }
22. }

Output:

 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.

Education4Fun.com
AWT Scrollbar class declaration
1. public class Scrollbar extends Component implements Adjustable, Accessible

Java AWT Scrollbar Example


1. import java.awt.*;
2. class ScrollbarExample{
3. ScrollbarExample(){
4. Frame f= new Frame("Scrollbar Example");
5. Scrollbar s=new Scrollbar();
6. s.setBounds(100,100, 50,100);
7. f.add(s);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. new ScrollbarExample();
14. }
15. }

Output:

 Java AWT TextField


The object of a TextField class is a text component that allows the editing of a single line text. It inherits TextComponent class.

AWT TextField Class Declaration


1. public class TextField extends TextComponent

Java AWT TextField Example


1. import java.awt.*;
2. class TextFieldExample{
3. public static void main(String args[]){
4. Frame f= new Frame("TextField Example");
5. TextField t1,t2;
6. t1=new TextField("Welcome to Javatpoint.");
7. t1.setBounds(50,100, 200,30);
8. t2=new TextField("AWT Tutorial");
9. t2.setBounds(50,150, 200,30);
10. f.add(t1); f.add(t2);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
14. }
15. }
Output:

Education4Fun.com
 Java AWT TextArea
The object of a TextArea class is a multi line region that displays text. It allows the editing of multiple line text. It inherits
TextComponent class.

AWT TextArea Class Declaration


1. public class TextArea extends TextComponent

Java AWT TextArea Example


1. import java.awt.*;
2. public class TextAreaExample
3. {
4. TextAreaExample(){
5. Frame f= new Frame();
6. TextArea area=new TextArea("Welcome to javatpoint");
7. area.setBounds(10,30, 300,300);
8. f.add(area);
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public static void main(String args[])
14. {
15. new TextAreaExample();
16. }
17. }

Output:

 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.

Education4Fun.com
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


1. public class MenuItem extends MenuComponent implements Accessible

AWT Menu class declaration


1. public class Menu extends MenuItem implements MenuContainer, Accessible

Java AWT MenuItem and Menu Example


1. import java.awt.*;
2. class MenuExample
3. {
4. MenuExample(){
5. Frame f= new Frame("Menu and MenuItem Example");
6. MenuBar mb=new MenuBar();
7. Menu menu=new Menu("Menu");
8. Menu submenu=new Menu("Sub Menu");
9. MenuItem i1=new MenuItem("Item 1");
10. MenuItem i2=new MenuItem("Item 2");
11. MenuItem i3=new MenuItem("Item 3");
12. MenuItem i4=new MenuItem("Item 4");
13. MenuItem i5=new MenuItem("Item 5");
14. menu.add(i1);
15. menu.add(i2);
16. menu.add(i3);
17. submenu.add(i4);
18. submenu.add(i5);
19. menu.add(submenu);
20. mb.add(menu);
21. f.setMenuBar(mb);
22. f.setSize(400,400);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26. public static void main(String args[])
27. {
28. new MenuExample();
29. }
30. }

Output:

Education4Fun.com
 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.

AWT Dialog class declaration


1. public class Dialog extends Window

Java AWT Dialog Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class DialogExample {
4. private static Dialog d;
5. DialogExample() {
6. Frame f= new Frame();
7. d = new Dialog(f , "Dialog Example", true);
8. d.setLayout( new FlowLayout() );
9. Button b = new Button ("OK");
10. b.addActionListener ( new ActionListener()
11. {
12. public void actionPerformed( ActionEvent e )
13. {
14. DialogExample.d.setVisible(false);
15. }
16. });
17. d.add( new Label ("Click button to continue."));
18. d.add(b);
19. d.setSize(300,300);
20. d.setVisible(true);
21. }
22. public static void main(String args[])
23. {
24. new DialogExample();
25. }
26. }

Output:

 AWT FileDialog Class


FileDialog control represents a dialog window from which the user can select a file.

Education4Fun.com
Class declaration
Following is the declaration for java.awt.FileDialog class:

public class FileDialog extends Dialog

Java FileDialog Example


import java.awt.*;

class SampleFrame extends Frame

SampleFrame(String title)

super(title);

class FileDialogDemo

public static void main(String args[])

Frame f = new SampleFrame("File Dialog Demo");

f.setVisible(true);

f.setSize(100, 100);

FileDialog fd = new FileDialog(f, "File Dialog");

fd.setVisible(true);

OUTPUT:

Education4Fun.com
AWT Layouts
Java LayoutManagers

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented
by all the classes of layout managers. There are following classes that represents the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

AWT Layout Manager Classes:

Following is the list of commonly used controls while designed GUI using
AWT.

Sr. LayoutManager & Description


No.

1 BorderLayout

The borderlayout arranges the components to fit in the five regions: east, west, north, south
and center.

2 CardLayout

The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.

3 FlowLayout

The FlowLayout is the default layout.It layouts the components in a directional flow.

4 GridLayout

The GridLayout manages the components in form of a rectangular grid.

5 GridBagLayout

This is the most flexible layout manager class.The object of GridBagLayout aligns the
component vertically,horizontally or along their baseline without requiring the components of
same size.

EXAMPLE:

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {

Education4Fun.com
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new Border();
26. }
27. }

OUTPUT:

HANDLING EVENTS BY EXTENDING AWT COMPONENTS

Java also allows us to handle events by subclassing AWT components. In order to extend an AWT component, we must call the enableEvents( )
method of Component. Its general form is shown here:

protected final void enableEvents(long eventMask)

The eventMask argument is a bit mask that defines the events to be delivered to this component. The AWTEvent class defines int constants for
making this mask. Several are shown here:

ACTION_EVENT_MASK
KEY_EVENT_MASK
ADJUSTMENT_EVENT_MASK
MOUSE_EVENT_MASK
COMPONENT_EVENT_MASK
MOUSE_MOTION_EVENT_MASK
CONTAINER_EVENT_MASK
MOUSE_WHEEL_EVENT_MASK
FOCUS_EVENT_MASK
TEXT_EVENT_MASK
INPUT_METHOD_EVENT_MASK
WINDOW_EVENT_MASK
ITEM_EVENT_MASK

Education4Fun.com
We must also override the appropriate method from one of our superclasses in order to process the event. Methods listed below most commonly
used and the classes that provide them.

 Java AWT Button Example with ActionListener


1. import java.awt.*;
2. import java.awt.event.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. Frame f=new Frame("Button Example");
6. final TextField tf=new TextField();
7. tf.setBounds(50,50, 150,20);
8. Button b=new Button("Click Here");
9. b.setBounds(50,100,60,30);
10. b.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to Javatpoint.");
13. }
14. });
15. f.add(b);f.add(tf);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
20. }

Output:

 Java AWT Label Example with ActionListener


1. import java.awt.*;
2. import java.awt.event.*;
3. public class LabelExample extends Frame implements ActionListener{
4. TextField tf; Label l; Button b;
5. LabelExample(){
6. tf=new TextField();
7. tf.setBounds(50,50, 150,20);
8. l=new Label();
9. l.setBounds(50,100, 250,20);
10. b=new Button("Find IP");
11. b.setBounds(50,150,60,30);
12. b.addActionListener(this);
13. add(b);add(tf);add(l);
14. setSize(400,400);
15. setLayout(null);

Education4Fun.com
16. setVisible(true);
17. }
18. public void actionPerformed(ActionEvent e) {
19. try{
20. String host=tf.getText();
21. String ip=java.net.InetAddress.getByName(host).getHostAddress();
22. l.setText("IP of "+host+" is: "+ip);
23. }catch(Exception ex){System.out.println(ex);}
24. }
25. public static void main(String[] args) {
26. new LabelExample();
27. }
28. }

 Java AWT TextArea Example with ActionListener


1. import java.awt.*;
2. import java.awt.event.*;
3. public class TextAreaExample extends Frame implements ActionListener{
4. Label l1,l2;
5. TextArea area;
6. Button b;
7. TextAreaExample(){
8. l1=new Label();
9. l1.setBounds(50,50,100,30);
10. l2=new Label();
11. l2.setBounds(160,50,100,30);
12. area=new TextArea();
13. area.setBounds(20,100,300,300);
14. b=new Button("Count Words");
15. b.setBounds(100,400,100,30);
16. b.addActionListener(this);
17. add(l1);add(l2);add(area);add(b);
18. setSize(400,450);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. String text=area.getText();
24. String words[]=text.split("\\s");
25. l1.setText("Words: "+words.length);
26. l2.setText("Characters: "+text.length());
27. }
28. public static void main(String[] args) {
29. new TextAreaExample();
30. }
31. }

Output:

Education4Fun.com
Education4Fun.com

You might also like