0% found this document useful (0 votes)
3 views36 pages

AWT Controls in Java With Examples

This document provides an overview of AWT (Abstract Window Toolkit) controls in Java, detailing various components such as Labels, Buttons, Canvas, Checkboxes, Radio Buttons, Choice, and List controls. Each control is explained with its constructors, methods, and examples to illustrate their usage in Java applications. The document serves as a comprehensive guide for understanding and implementing AWT controls in Java programming.

Uploaded by

ayushmaurya155
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views36 pages

AWT Controls in Java With Examples

This document provides an overview of AWT (Abstract Window Toolkit) controls in Java, detailing various components such as Labels, Buttons, Canvas, Checkboxes, Radio Buttons, Choice, and List controls. Each control is explained with its constructors, methods, and examples to illustrate their usage in Java applications. The document serves as a comprehensive guide for understanding and implementing AWT controls in Java programming.

Uploaded by

ayushmaurya155
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

AWT Controls in Java with Examples

In this article, I am going to discuss AWT Controls in Java with


Examples. Please read our previous article, where we
discussed Abstract Windows Toolkit (AWT) in Java. At the end of this
article, you will understand the following pointers in detail which are
related to AWT Controls in java with Examples.
1. AWT Controls in Java
2. Labels
3. Buttons
4. Canvas
5. Checkbox
6. Radio Buttons
7. AWT Choice Control in Java
8. List Control
9. AWT Scroll Bar Control in java
10. AWT TextComponent Controls in Java

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.awt.event.*;
public class Main
{
void main ()
{
Frame f = new Frame ("Main Window");
Label lb1 = new Label ("Label 1",Label.CENTER);
Label lb2 = new Label ("Label 2",Label.LEFT);
lb1.setSize(100,100);
lb2.setSize(100,100);

lb1.setBackground(Color.red);
f.add (lb1);
f.add (lb2);

f.setVisible (true);
f.setSize (500, 400);

//f.dispose();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
}
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
• Checkbox() throws HeadlessException: Creates a checkbox

whose label is initially blank. The state of the checkbox is


unchecked.
• Checkbox(String str) throws HeadlessException: Creates a

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


checkbox is unchecked.
• 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.
• 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.*;

public class CheckboxDemo extends Frame implements ItemListener


{
String msg = "";
Checkbox winXP, winVista, solaris, mac;

public CheckboxDemo() {
setTitle("Checkbox Demo");
setSize(250, 200);

// Create checkboxes
winXP = new Checkbox("Windows XP", true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");

// Set layout
setLayout(new FlowLayout());

// Add checkboxes to frame


add(winXP);
add(winVista);
add(solaris);
add(mac);

// Add item listeners


winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);

// Add window listener to handle closing


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public void itemStateChanged(ItemEvent ie) {


repaint();
}

public void paint(Graphics g) {


msg = "Current state: ";
g.drawString(msg, 20, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 20, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 20, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 20, 140);
msg = " Mac OS: " + mac.getState();
g.drawString(msg, 20, 160);
}

public static void main(String[] args) {


CheckboxDemo app = new CheckboxDemo();
app.setVisible(true);
}
}

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:

package javaapplication22;

import java.awt.*;
import java.awt.event.*;

public class JavaApplication22 extends Frame implements


ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
CheckboxGroup cbg;

public JavaApplication22() {
setTitle("Radio Button Demo");
setSize(250, 200);
setLayout(new FlowLayout());

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

// Close the window when clicked on X


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

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, 20, 120);
}
public static void main(String[] args) {
JavaApplication22 demo = new JavaApplication22();
demo.setVisible(true);
}
}

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.*;

public class Main extends Frame implements ItemListener {


Choice os, browser;
String msg = "";

public Main() {
setTitle("Choice Demo");
setSize(300, 180);
setLayout(new FlowLayout());

// Create choice components


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

// Add window listener to handle closing


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public void itemStateChanged(ItemEvent ie) {


repaint();
}

public void paint(Graphics g) {


msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 20, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 20, 140);
}

public static void main(String[] args) {


Main demo = new Main();
demo.setVisible(true);
}
}
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.*;

public class Main extends Frame implements ActionListener {


List os, browser;
String msg = "";

public Main()
{
setTitle("List Demo");
setBackground(Color.yellow);
setSize(300, 180);
setLayout(new FlowLayout());

// Create list components


os = new List(4, true); // 4 visible rows, multiple selection
allowed
browser = new List(4, false); // 4 visible rows, single selection
only

// 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); // Select Firefox initially (index 1)

// Add lists to window


add(os);
add(browser);

// Register to receive action events


os.addActionListener(this);
browser.addActionListener(this);

// Add window listener to handle closing


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public void actionPerformed(ActionEvent ae) {


repaint();
}

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, 20, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 20, 140);
}

public static void main(String[] args) {


Main demo = new Main();
demo.setVisible(true);
}
}
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 getMinimum(): 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.*;

public class Main extends Frame implements AdjustmentListener,


MouseMotionListener {
String msg = "";
Scrollbar vertSB, horzSB;
final int DEFAULT_WIDTH = 300;
final int DEFAULT_HEIGHT = 200;

public Main() {
setTitle("Scrollbar Demo");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setLayout(new BorderLayout());

// Create scrollbars
vertSB = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0,
DEFAULT_HEIGHT);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0,
DEFAULT_WIDTH);

// Add scrollbars to frame


add(vertSB, BorderLayout.EAST);
add(horzSB, BorderLayout.SOUTH);

// Register listeners
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);

// Handle window closing


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public void adjustmentValueChanged(AdjustmentEvent ae) {


repaint();
}

public void mouseDragged(MouseEvent me) {


int x = me.getX();
int y = me.getY();
vertSB.setValue(y);
horzSB.setValue(x);
repaint();
}

public void mouseMoved(MouseEvent me) {


// Necessary for MouseMotionListener
}
public void paint(Graphics g) {
// Display current values of scrollbars
msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 20, 160);

// Show current mouse drag position


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

public static void main(String[] args) {


Main demo = new Main();
demo.setVisible(true);
}
}
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 :
TextField 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.*;

public class Main extends Frame implements ActionListener {


TextField name, pass;
public Main() {
setTitle("TextField Demo");
setSize(380, 150);
setLayout(new FlowLayout(FlowLayout.LEFT));

// Create labels and text fields


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 components to frame


add(namep);
add(name);
add(passp);
add(pass);

// Register action listeners


name.addActionListener(this);
pass.addActionListener(this);

// Handle window closing


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
// User pressed Enter
public void actionPerformed(ActionEvent ae) {
repaint();
}

public void paint(Graphics g) {


g.drawString("Name: " + name.getText(), 20, 80);
g.drawString("Selected text in name: " + name.getSelectedText(),
20, 100);
g.drawString("Password: " + pass.getText(), 20, 120);
}

public static void main(String[] args) {


Main demo = new Main();
demo.setVisible(true);
}
}
Output

Here, you will get a response when the user will press ENTER.
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.awt.event.*;

public class Main extends Frame {

Font fnt = new Font("Areal",Font.BOLD,18);


public Main() {
// Set frame properties
setTitle("TextArea Demo");
setSize(550, 450);
setBackground(Color.yellow);
setFont(fnt);
setLayout(new FlowLayout());

// Create the text content


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.";

// Create TextArea with 15 rows and 30 columns


TextArea text = new TextArea(val, 15, 40);
text.setBackground(Color.cyan);

add(text);

// Add window listener to handle closing


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public static void main(String[] args) {


Main demo = new Main();
demo.setVisible(true);
}
}
Output

You might also like