Abstract Windows Toolkit

You might also like

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

Abstract Windows Toolkit (AWT) in Java

Abstract Windows Toolkit (AWT) in Java:

AWT package is bundled with Java software by default, i.e., located in rt.jar file (jre/lib).
AWT package is platform dependent API used for creating a graphical user interface.
The AWT contains a number of classes and methods that allow you to create and
manage windows. It is also the foundation to build Swing. When a user wants to interact
with an application, the user has to provide some information to the application and it
can be done in two ways:

 Character User Interface(CUI): This interface is used to interact with the


application by typing some characters. This interface is not user friendly because
the user has to type all the commands and the user has to remember all the
commands. Example: DOS

 Graphical User Interface(GUI): This interface will interact with the application by
using some graphics like menus, icons, images, etc. This interface is user friendly
because it prompts the user by providing the options or menus. Example:
Windows XP, Windows 7, etc.

Points To Remember:

1. To develop the GUI based applications we have to use AWT.


2. AWT stands for Abstract Windowing Toolkit.
3. The set of classes and interfaces which are required to develop GUI components
together are called “Toolkit”. The GUI components will be used to design GUI
programs.
4. Writing a program to display the created GUI components on the windows is
called “windowing”.
5. To display the components on the windows we need to take the support of
graphics available in the operating system. For a developer, there is no direct
interaction with the graphics and hence graphics is “Abstract” to the developer.
6. Every GUI component will have a corresponding “PEER” class which is
responsible to interact with the graphics of the operating system.

Why AWT is platform-dependent?


Java AWT components are platform-dependent because components are displayed
according to the view of the operating system. Java AWT calls Operating systems
subroutine for creating components such as textbox, button, etc. An application built on
AWT looks like a windows application when it runs on Windows, but the same
application would look like a Mac application when runs on Mac OS.

Note: AWT is rarely used nowadays because of its platform-dependent and heavy-
weight nature. AWT components are considered heavyweight because they are being
generated by the underlying operating system(OS).

Advantages of GUI over CUI

1. They are easy to learn and use, i.e. users without experience can also use the
system quickly.
2. The user can interact with several different applications by switching quickly from
one task to another.
3. Information remains visible in its own window when attention is switched.
4. Fast, full-screen interaction is possible with immediate access to anywhere on the
screen.
5. Some types of error situations can be avoided because they are not allowed to
occur through input.

Features of AWT in Java:

The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI)
programming. AWT features include:

 It is a set of native user interface components


 It is a robust event-handling model
 Applets have graphics and imaging tools, including shape, color, and font classes
 The applet is having layout managers, for flexible window layouts that do not
depend on a particular window size or screen resolution
 The applet contains Data transfer classes, for cut-and-paste through the native
platform clipboard

AWT UI Aspects

Every user interface considers the following three main aspects:

1. UI Elements: It refers to the core visual elements used for interacting with the
applications and which are visible to the users.

2. Layouts: It defines how UI elements should be organized on the screen and


provide a final look and feel to the GUI.

3. Behavior: It defines the events which should occur when a user interacts with UI
elements.
AWT Hierarchy in Java

The AWT classes are contained in java.awt package. It is one of Java’s largest
packages. Fortunately, because it is logically organized in a top-down, hierarchical
fashion, it is easier to understand and use than you might at first believe.
The AWT defines windows according to a class hierarchy that is used to add
functionality and specificity to each level. The two most common windows are Panel,
which is used by applets, and Frame, which creates a standard application window.
Most of the functionalities of these windows are derived from their parent classes.

AWT Component in Java

At the top of the AWT, the hierarchy is the component class. The Component is an
abstract class that encapsulates all of the attributes of a visual component. All user
interface elements that interact with the user are subclasses of Component and are
displayed on the screen.

Some useful methods of Component Class

1. public void add(Component c): It is used to insert a component on this


component.
2. public void setSize(int width, int height): It is used to set the size (height and
width) of the component.
3. public void setLayout(LayoutManager m): It defines the layout manager of the
component.
4. public void setStatus(boolean status): It is used to change the visibility of the
component, by default false.

Container
The Container class is a subclass of the Component class. It has additional methods
that allow other component objects to be nested within it. A container provides a space
where a component can be located. A Container in AWT is a component itself and it
adds the capability to add the component to itself.

Panel
The Panel class is a concrete subclass of Container. It provides space in which an
application can attach any other component. The default layout manager for a panel is
the FlowLayout layout manager. It is visually represented as a window that does not
contain a title bar, menu bar, or border. Panels don’t have any visible bounding lines.
You can delimit them with different background colors.

Window
The Window class creates a top-level window with no border and no menubar. It uses
BorderLayout as a default layout manager. A window must have either a frame, dialog,
or another window defined as its owner when it’s constructed. It could be used to
implement a pop-up menu. A Window object blocks input to other application windows
when it is shown.

Dialog
Dialog class’s instance always needs an associated Frame class instance to exist.
Dialog class is also a subclass of Window and comes with the border as well as the title.
An instance of the Dialog class cannot exist without an associated instance of the Frame
class.

Frame
A-Frame may be a top-level window with a title and a border. It can produce other
components like buttons, text fields, etc. The default layout for a frame is BorderLayout.
Frames are capable of generating the subsequent sorts of window events:
WindowOpened, WindowClosing, WindowClosed, WindowIconified, WindowDeiconified,
WindowActivated, WindowDeactivated. When a Frame window is made by a stand-
alone application instead of an applet, a traditional window is made.

Frame’s Constructors

Here are two of Frame’s constructors:


1. Frame(): It creates a standard window that does not contain a title.
2. Frame(String title): It creates a window with the title specified by the title.
Note: You cannot specify the dimensions of the window. Instead, you must set the size
of the window after it has been created.

Methods of Frames

1. void setSize(int newWidth, newHeight): It is used to set the dimensions of the


window by specifying the width and height fields of the dimensions. The
dimensions are specified in terms of pixels.

2. void setSize(Dimension newSize): The new size of the window is specified by


newWidth and newHeight, or by the width and height fields of the Dimension
object passed in newSize.

3. Dimension getSize() : The getSize() method is used to obtain the current size of
a window. This method returns the current size of the window contained within
the width and height fields of a Dimension object.

4. void setVisible(Boolean visibleFlag): The component is visible of the argument


to this method is true. Otherwise, it is hidden.

5. void setTitle(String newTitle): You can change the title in a frame window using
setTitle(). Here, newTitle is the new title for the window.

6. windowClosing(): When using a frame window, your program must remove that
window from the screen when it is closed, by calling setVisible(false). To intercept
a window-close event, you must implement the windowClosing() method of the
WindowListener interface. Inside windowClosing(), you must remove the window
from the screen.

Creating a Frame Window in an Applet

The frame can be created in two ways:

1. Create the object of the Frame class directly.

Frame f = new Frame();

2. Create the object of any class that extends the Frame class.

MyFrame mf = new MyFrame();


Example to create a frame by creating the object of the frame class directly
using AWT in Java

import java.awt.*;

public class FrameDemo1

public static void main (String[]args)

Frame f = new Frame (“demo frame”);

Label lb = new Label ("Hello World");

f.add (lb);

f.setVisible (true);

f.setSize (300, 300);

}
}

Output:
Example to create a frame by extending the frame class using AWT in Java

import java.awt.*;

public class FrameDemo2 extends Frame

public static void main (String[]args)

FrameDemo2 fd = new FrameDemo2 ();

Button btn = new Button ("Hello World");

fd.add (btn);

fd.setVisible (true);

fd.setSize (500, 200);

}
}

Output:
AWT Controls in Java:

Controls are components that allow a user to interact with your application in various
ways. The AWT supports the following types of controls:

Labels

The easiest control to use is a label. A label contains a string and is an object of type
Label. Labels are passive controls that do not support any interaction with the user.

Creating Label : Label l = new Label(String);

Label Constructors:

1. Label() throws HeadlessException: It creates a blank label.


2. Label(String str) throws HeadlessException: It creates a label that contains
the string specified by str.
3. Label(String str, int how): It 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.

Label Methods:
1. void setText(String str): It is used to set or change the text in a label by using
the setText() method. Here, str specifies the new label.
2. String getText(): It is used to obtain the current label by calling getText()
method. Here, the current label is returned.
3. void setAlignment(int how): It is used to set the alignment of the string within
the label by calling setAlignment() method. Here, how is one of the alignment
constants?
4. int getAlignment(): It is used to obtain the current alignment, getAlignment() is
called.

Example to understand AWT Label Control in Java:

import java.awt.*;
import java.applet.*;

/*
<applet code = "LabelDemo" width=300 height=200>
</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 (one);
add (two);
add (three);
}
}

Output:

AWT Button Control in Java

The most widely used control is Button. A button is a component that contains a label
and that generates an event when it is pressed.

Creating Button : Button b = new Button(String label);

Button Constructors:

1. Button() throws HeadlessException: It creates an empty button.

2. Button(String str) throws HeadlessException: It creates a button that contains


str as a label.

Button Methods :

1. void setLabel(String str): You can set its label by calling setLabel(). Here, str is
the new Label for the button.
2. String getLabel(): You can retrieve its label by calling getLabel() method.
Example to understand AWT Button Control in Java:

import java.awt.*;

import java.awt.event.*;

public class ButtonDemo extends Frame

Button b1, b2;

ButtonDemo ()

b1 = new Button ("OK");

b2 = new Button ("CANCEL");

this.setLayout (null);

b1.setBounds (100, 100, 80, 40);;

b2.setBounds (200, 100, 80, 40);

this.add (b1);

this.add (b2);

this.setVisible (true);

this.setSize (300, 300);

this.setTitle ("button");

this.addWindowListener (new WindowAdapter ()

public void windowClosing (WindowEvent we)

System.exit (0);

}
});

public static void main (String args[])

new ButtonDemo ();

Output:

AWT Canvas Control in java


Canvas encapsulates a blank window upon which you can draw in an application or
receive inputs created by the user.

Canvas Constructor:

1. Canvas() : Constructs a new Canvas.


2. Canvas (GraphicsConfiguration config) : Constructs a new Canvas given a
GraphicsConfiguration object.

Canvas Methods:

1. void addNotify(): It is used to create the peer of the canvas.


2. void createBufferStrategy(int numBuffers): It is used to create a new strategy
for multi-buffering on this component.
3. BufferStrategy getBufferStrategy(): It is used to return the BufferStrategy used
by this component.

Example to understand AWT Canvas Control in Java:

import java.awt.*;

import java.awt.event.*;
public class CanvasDemo

private Frame mainFrame;

private Label headerLabel;

private Label statusLabel;

private Panel controlPanel;

public CanvasDemo ()

prepareGUI ();

public static void main (String[]args)

CanvasDemo awtControlDemo = new CanvasDemo ();

awtControlDemo.showCanvasDemo ();

private void prepareGUI ()

mainFrame = new Frame ("Java AWT Examples");

mainFrame.setSize (400, 400);

mainFrame.setLayout (new GridLayout (3, 1));

mainFrame.addWindowListener (new WindowAdapter ()

public void windowClosing (WindowEvent windowEvent)

{
System.exit (0);

});

headerLabel = new Label ();

headerLabel.setAlignment (Label.CENTER);

statusLabel = new Label ();

statusLabel.setAlignment (Label.CENTER);

statusLabel.setSize (350, 100);

controlPanel = new Panel ();

controlPanel.setLayout (new FlowLayout ());

mainFrame.add (headerLabel);

mainFrame.add (controlPanel);

mainFrame.add (statusLabel);

mainFrame.setVisible (true);

private void showCanvasDemo ()

headerLabel.setText ("Control in action: Canvas");

controlPanel.add (new MyCanvas ());

mainFrame.setVisible (true);

class MyCanvas extends Canvas

public MyCanvas ()
{

setBackground (Color.GRAY);

setSize (300, 300);

public void paint (Graphics g)

Graphics2D g2;

g2 = (Graphics2D) g;

g2.drawString ("It is a custom canvas area", 70, 70);

Output:
AWT Checkbox Control in java

A checkbox may be a control that’s used to turn an option on or off. It consists of a little
box that will either contain a check or not. There’s a label related to each checkbox that
describes what option the box represents. You modify the state of a checkbox by
clicking on. Checkboxes are often used individually or as a part of a gaggle. Checkboxes
are objects of the Checkbox class.

Creating Checkbox : Checkbox cb = new Checkbox(Label);

Checkbox Constructor

1. Checkbox() throws HeadlessException: Creates a checkbox whose label is


initially blank. The state of the checkbox is unchecked.

2. Checkbox(String str) throws HeadlessException: Creates a checkbox whose


label is specified by str. The state of the checkbox is unchecked.

3. Checkbox(String str, Boolean on) throws HeadlessException: It allows you


to line the initial state of the checkbox. If one is true, the checkbox is initially
checked; otherwise, it’s cleared.

4. Checkbox(String str, Boolean on, CheckboxGroup cbGroup) throws


HeadlessException or Checkbox(String str, CheckboxGroup cbGroup,
Boolean on) throws HeadlessException: It creates a checkbox whose label is
specified by str and whose group is specified by cbGroup. If this checkbox isn’t a
part of a gaggle, then cbGroup must be null. the worth of on determines the initial
state of the checkbox.

Methods of Checkbox

1. boolean getState(): To retrieve the present state of a checkbox.

2. void setState(boolean on): To line its state, call setState(). Here, if one is true,
the box is checked. If it’s false, the box is cleared.

3. String getLabel(): you’ll obtain the present label related to a checkbox by calling
getLabel().

4. void setLabel(String str): To line the label, call setLabel(). The string passed in
str becomes the new label related to the invoking checkbox.
Example to understand AWT Checkbox Control in Java:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code="CheckboxDemo" width=250 height=200> </applet> */

public class CheckboxDemo extends Applet implements ItemListener

String msg = "";

Checkbox winXP, winVista, solaris, mac;

public void init ()

winXP = new Checkbox ("Windows XP", null, true);

winVista = new Checkbox ("Windows Vista");

solaris = new Checkbox ("Solaris");

mac = new Checkbox ("Mac OS");

add (winXP);

add (winVista);

add (solaris);

add (mac);

winXP.addItemListener (this);

winVista.addItemListener (this);

solaris.addItemListener (this);

mac.addItemListener (this);

}
public void itemStateChanged (ItemEvent ie)

repaint ();

public void paint (Graphics g)

msg = "Current state: ";

g.drawString (msg, 6, 80);

msg = " Windows XP: " + winXP.getState ();

g.drawString (msg, 6, 100);

msg = " Windows Vista: " + winVista.getState ();

g.drawString (msg, 6, 120);

msg = " Solaris: " + solaris.getState ();

g.drawString (msg, 6, 140);

msg = " Mac OS: " + mac.getState ();

g.drawString (msg, 6, 160);

Output:
CheckboxGroup: Radio Buttons

It is possible to make a group of mutually exclusive checkboxes during which one and just
one checkbox up the group are often checked at anybody time. These checkboxes are
often called radio buttons because they act just like the station selector on a car radio,
only one station is often selected at anybody’s time. To create a group of mutually
exclusive checkboxes, you want to first define the group to which they’re going to belong
then specify that group once you construct the checkboxes. Checkbox groups are objects
of the type CheckboxGroup. Only the default constructor is defined, which creates an
empty group.

Creating Radiobutton :

CheckboxGroup cbg = new CheckboxGroup();

Checkbox rb = new Checkbox(Label, cbg, boolean);

CheckboxGroup Methods

1. Checkbox getSelectedCheckbox(): You can determine which checkbox in a


group is currently selected by calling getSelectedCheckbox().

2. void setSelectedCheckbox(Checkbox which): You can set a checkbox by


calling setSelectedCheckbox(). Here, is the checkbox that you simply want to be
selected. The previously selected checkbox is going to be turned off.
Example to understand AWT CheckboxGroup Control in Java:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code="CBGroup" width=250 height=200> </applet> */

public class RadiobuttonDemo extends Applet implements ItemListener

String msg = "";

Checkbox winXP, winVista, solaris, mac;

CheckboxGroup cbg;

public void init ()

cbg = new CheckboxGroup ();

winXP = new Checkbox ("Windows XP", cbg, true);

winVista = new Checkbox ("Windows Vista", cbg, false);

solaris = new Checkbox ("Solaris", cbg, false);

mac = new Checkbox ("Mac OS", cbg, false);

add (winXP);

add (winVista);

add (solaris);

add (mac);

winXP.addItemListener (this);

winVista.addItemListener (this);

solaris.addItemListener (this);

mac.addItemListener (this);
}

public void itemStateChanged (ItemEvent ie)

repaint ();

// Display current state of the check boxes.

public void paint (Graphics g)

msg = "Current selection: ";

msg += cbg.getSelectedCheckbox ().getLabel ();

g.drawString (msg, 6, 100);

Output:

AWT Choice Control in Java

This component will display a group of times as a drop-down menu from which a user
can select only one item. The choice component is used to create a pop-up list of items
from which the user may choose. Therefore, Choice control is a form of a menu. When it
is inactive, a Choice component takes up only enough space to show the currently
selected item. When the user clicks on a Choice component, the whole list of choices
pops up, and a new selection can be made.

Note: Choice only defines the default constructor, which creates an empty list.
Creating Choice : Choice ch = new Choice();

Choice Methods

1. void add(String name): To add a selection to the list, use add(). Here, the name
is the name of the item being added.
2. String getSelectedItem(): It determines which item is currently selected. It
returns a string containing the name of the item.
3. int getSelectedIndex(): It determines which item is currently selected. It returns
the index of the item.
4. int getItemCount(): It obtains the number of items in the list.
5. void select(int index): It is used to set the currently selected item with a zero-
based integer index.
6. void select(String name): It is used to set the currently selected item with a
string that will match a name in the list.
7. String getItem(int index): It is used to obtain the name associated with the item
at the given index. Here, the index specifies the index of the desired items.

Example to understand AWT Choice Control in Java:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ChoiceDemo" width=300 height=180> </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 XP");
os.add ("Windows Vista");
os.add ("Solaris");
os.add ("Mac OS");

// add items to browser list


browser.add ("Internet Explorer");
browser.add ("Firefox");
browser.add ("Opera");
browser.add ("Chrome");

// 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);
}
}
Output:

AWT List Control in Java:

This component will display a group of items as a drop-down menu from which a user
can select only one item. The List class provides a compact, multiple-choice, scrolling
selection list. Unlike the selection object, which shows only the only selected item within
the menu, an inventory object is often constructed to point out any number of choices
within the visible window. It also can be created to permit multiple selections.

Creating List : List l = new List(int, Boolean);

List Constructor
1. List() throws HeadlessException: It creates a list control that allows only one
item to be selected at any one time.
2. List(int numRows) throws HeadlessException: Here, the value of numRows
specifies the number of entries in the list that will always be visible.
3. List(int numRows, boolean multipleSelect) throws HeadlessException: If
multipleSelect is true, then the user may select two or more items at a time. If it’s
false, then just one item could also be selected.

Method of Lists

1. void add(String name): To add a selection to the list, use add(). Here, the name
is the name of the item being added. It adds items to the end of the list.
2. void add(String name, int index): It also adds items to the list but it adds the
items at the index specified by the index.
3. String getSelectedItem(): It determines which item is currently selected. It
returns a string containing the name of the item. If more than one item is
selected, or if no selection has been made yet, null is returned.
4. int getSelectedIndex(): It determines which item is currently selected. It returns
the index of the item. The first item is at index 0. If more than one item is
selected, or if no selection has yet been made, -1 is returned.
5. String[] getSelectedItems(): It allows multiple selections. It returns an array
containing the names of the currently selected items.
6. int[] getSelectedIndexes(): It also allows multiple selections. It returns an array
containing the indexes of the currently selected items.
7. int getItemCount(): It obtains the number of items in the list.
8. void select(int index): It is used to set the currently selected item with a zero-
based integer index.
9. String getItem(int index): It is used to obtain the name associated with the item
at the given index. Here, the index specifies the index of the desired items.

Example to understand AWT List Control in Java:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code="ListDemo" width=300 height=180> </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 XP");

os.add ("Windows Vista");

os.add ("Solaris");

os.add ("Mac OS");


// add items to browser list

browser.add ("Internet Explorer");

browser.add ("Firefox");

browser.add ("Opera");

browser.select (1);

// add lists to window

add (os);

add (browser);

// register to receive action 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);

Output:

AWT Scroll Bar Control in java

Scrollbars are used to select continuous values between a specified minimum and
maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is really a
composite of several individual parts. Each end has an arrow that you simply can click to
get the present value of the scroll bar one unit within the direction of the arrow. The
current value of the scroll bar relative to its minimum and maximum values are indicated
by the slider box for the scroll bar. Scrollbars are encapsulated by the Scrollbar class.

Creating Scrollbar : Scrollbar sb = new Scrollbar();

Scrollbar Constructor

1. Scrollbar() throws HeadlessException: It creates a vertical scrollbar.

2. Scrollbar(int style) throws HeadlessException: It allows you to specify the


orientation of the scrollbar. If the style isScrollbar.VERTICAL, a vertical scrollbar
is created. If a style is Scrollbar.HORIZONTAL, the scroll bar is horizontal.
3. Scrollbar(int style, int initialValue, int thumbSize, int min, int max) throws
HeadlessException: Here, the initial value of the scroll bar is passed in
initialValue. The number of units represented by the peak of the thumb is passed
in thumbSize. The minimum and maximum values for the scroll bar are specified
by min and max.

Scrollbar Methods

1. void setValues(int initialValue, int thumbSize, int min, int max): It is used to
set the parameters of the constructors.

2. int getValue(): It is used to obtain the current value of the scroll bar. It returns the
current setting.

3. void setValue(int newValue): It is used to set the current value. Here, newValue
specifies the new value for the scroll bar. When you set a worth, the slider box
inside the scroll bar is going to be positioned to reflect the new value.

4. int getMaximum(): It is used to retrieve the minimum values. They return the
requested quantity. By default, 1 is the increment added to the scroll bar.

5. int getMaximun(): It is used to retrieve the maximum value. By default, 1 is the


increment subtracted from the scroll bar.

Example to understand AWT Scrollbar Control in Java:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code="SBDemo" width=300 height=200> </applet> */

public class ScrollbarDemo 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, height);

horzSB = new Scrollbar (Scrollbar.HORIZONTAL, 0, 1, 0, width);

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, 6, 160);

//show current mouse drag position

g.drawString ("*", horzSB.getValue (), vertSB.getValue ());

}}

Output

AWT TextComponent Control in Java


The TextComponent class is the superclass of any component that permits the editing of
some text. A text component embodies a string of text. The TextComponent class
defines a group of methods that determine whether or not this text is editable. There are
two types of TextComponent:

1. TextField

2. TextArea

AWT TextField Control in Java

The TextField component will allow the user to enter some text. It is used to implement a
single-line text-entry area, usually called an edit control. It also allows the user to enter
strings and edit the text using the arrow keys, cut and paste keys, and mouse selections.
TextField is a subclass of TextComponent.

Creating TextField : TextFielf tf = new TextField(size);

TextField Constructors

1. TextField() throws HeadlessException: It creates a default textfield.

2. TextField(int numChars) throws HeadlessException: It creates a text field that


is numChars characters wide.

3. TextField(String str) throws HeadlessException: It initializes the text field with


the string contained in str.

4. TextField(String str, int numChars) throws HeadlessException: It initializes a


text field and sets its width.

TextField Methods

1. String getText(): It is used to obtain the string currently contained in the text
field.

2. void setText(String str): It is used to set the text. Here, str is the new String.

3. void select(int startIndex, int endIndex): It is used to select a portion of the text
under program control. It selects the characters beginning at startIndex and
ending at endIndex-1.

4. String getSelectedText(): It returns the currently selected text.


5. boolean isEditable(): It is used to determine editability. It returns true if the text
may be changed and false if not.

6. void setEditable(boolean canEdit): It is used to control whether the contents of


a text field may be modified by the user. If canEdit is true, the text may be
changed. If it is false, the text cannot be altered.

7. void setEchoChar(char ch): It is used to disable the echoing of the characters


as they are typed. This method specifies a single character that TextField will
display when characters are entered.

8. boolean echoCharIsSet(): By this method, you can check a text field to see if it
is in this mode.

9. char getEchochar(): It is used to retrieve the echo character.

Example to understand AWT TextFiled Control in Java:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="TextFieldDemo" width=380 height=150> </applet>

*/

public class TextfieldDemo extends Applet implements ActionListener

TextField name, pass;

public void init ()

Label namep = new Label ("Name: ", Label.RIGHT);

Label passp = new Label ("Password: ", Label.RIGHT);

name = new TextField (12);

pass = new TextField (8);


pass.setEchoChar ('?');

add (namep);

add (name);

add (passp);

add (pass);

//register to receive action events

name.addActionListener (this);

pass.addActionListener (this);

//User pressed Enter.

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);

Output
AWT TextArea Control in Java

Sometimes one line of text input isn’t enough for a given task. To handle these
situations, the AWT includes an easy multiline editor called TextArea.

Creating TextArea : TextArea ta = new TextArea();

TextArea Constructor

1. TextArea() throws HeadlessException: It creates a default textarea.

2. TextArea(int numLines, int numChars) throws HeadlessException: It creates


a text area that is numChars characters wide. Here, numLines specifies the
height, in lines of the text area.

3. TextArea(String str) throws HeadlessException: It initializes the text area with


the string contained in str.

4. TextArea(String str, int numLines, int numChars) throws


HeadlessException: It initializes a text field and sets its width. Initial text can be
specified by str.

5. TextArea(String str, int numLines, int numChars, int sBars) throws


HeadlessException: Here, you can specify the scroll bars that you want the
control to have. sBars must be one of these values :

1. SCROLLBARS_BOTH
2. SCROLLBARS_NONE
3. SCROLLBARS_HORIZONTAL_ONLY
4. SCROLLBARS_VERTICAL_ONLY
TextArea Methods

TextArea is a subclass of TextComponent. Therefore, it supports the getText(


), setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods
described in the TextField section.
TextArea adds the following methods:

1. void append(String str): It appends the string specified by str to the end of the
current text.
2. void insert(String str, int index): It inserts the string passed in str at the
specified index.
3. voidReplaceRange(String str, int startIndex, int endIndex): It is used to
replace the text. It replaces the characters from startIndex to endIndex-1.

Example to understand AWT TextArea Control in Java:

import java.awt.*;
import java.applet.*; /* <applet code="TextAreaDemo" width=300 height=250> </applet>
*/

public class TextAreaDemo extends Applet {


public void init() {
String val = "Java SE 6 is the latest version of the most\n"
+ "widely-used computer language for Internet programming.\n"
+ "Building on a rich heritage, Java has advanced both\n"
+ "the art and science of computer language design.\n\n"
+ "One of the reasons for Java's ongoing success is its\n"
+ "constant, steady rate of evolution. Java has never stood\n"
+ "still. Instead, Java has consistently adapted to the\n"
+ "rapidly changing landscape of the networked world.\n"
+ "Moreover, Java has often led the way, charting the\n" + "course for others to
follow.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}

Output

You might also like