0% found this document useful (0 votes)
52 views

Java Abstract Window Toolkit

jwt

Uploaded by

santo nino
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Java Abstract Window Toolkit

jwt

Uploaded by

santo nino
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Java Abstract Window Toolkit(AWT)

Java AWT is an API that contains large number of classes and methods to create and manage graphical user interface ( GUI )
applications. The AWT was designed to provide a common set of tools for GUI design that could work on a variety of platforms.
The tools provided by the AWT are implemented using each platform's native GUI toolkit, hence preserving the look and feel of
each platform. This is an advantage of using AWT. But the disadvantage of such an approach is that GUI designed on one
platform may look different when displayed on another platform that means AWT component are platform dependent.
AWT is the foundation upon which Swing is made i.e Swing is a improved GUI API that extends the AWT. But now a days AWT is
merely used because most GUI Java programs are implemented using Swing because of its rich implementation of GUI controls
and light-weighted nature.
Powered By

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below, all the classes are available in java.awt package.

Component class
Component class is at the top of AWT hierarchy. It is an abstract class that encapsulates all the attributes of visual component. A
component object is responsible for remembering the current foreground and background colors and the currently selected
text font.
Container
Container is a component in AWT that contains another component like button, text field, tables etc. Container is a subclass of
component class. Container class keeps track of components that are added to another component.
Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or border. It is container that is used
for holding components.
Window class
Window class creates a top level window. Window does not have borders and menubar.
Frame
Frame is a subclass of Window and have resizing canvas. It is a container that contain several different components like button,
title bar, textfield, label etc. In Java, most of the AWT applications are created using Frame window. Frame class has two
different constructors,
Frame() throws HeadlessException
Frame(String title) throws HeadlessException
Creating a Frame
There are two ways to create a Frame. They are,
By Instantiating Frame class
By extending Frame class
Creating Frame Window by Instantiating Frame class
import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}

Creating Frame window by extending Frame class


package testawt;

import java.awt.*;
import java.awt.event.*;
1
public class Testawt extends Frame
{
public Testawt()
{
Button btn=new Button("Hello World");
add(btn); //adding a new Button.
setSize(400, 500); //setting size.
setTitle("StudyTonight"); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.
}

public static void main (String[] args)


{
Testawt ta = new Testawt(); //creating a frame.
}
}

Points to Remember:
While creating a frame (either by instantiating or extending Frame class), Following two attributes are must for visibility of the
frame:
setSize(int width, int height);
setVisible(true);
When you create other components like Buttons, TextFields, etc. Then you need to add it to the frame by using the method -
add(Component's Object);
You can add the following method also for resizing the frame - setResizable(true);

AWT Button
In Java, AWT contains a Button Class. It is used for creating a labelled button which can perform an action.
AWT Button Classs Declaration:
public class Button extends Component implements Accessible
Example:
Lets take an example to create a button and it to the frame by providing coordinates.

import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("studytonight ==> Button Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
}

AWT Label
In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single line text is allowed and the text can not
be changed directly.
Label Declaration:
public class Label extends Component implements Accessible
Example:
In this example, we are creating two labels to display text to the frame.
2
import java.awt.*;
class LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("studytonight ==> Label Demo");
Label lab1,lab2;
lab1=new Label("Welcome to studytonight.com");
lab1.setBounds(50,50,200,30);
lab2=new Label("This Tutorial is of Java");
lab2.setBounds(50,100,200,30);
l_Frame.add(lab1);
l_Frame.add(lab2);
l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
}
}

AWT TextField
In Java, AWT contains aTextField Class. It is used for displaying single line text.
TextField Declaration:
public class TextField extends TextComponent
Example:
We are creating two textfields to display single line text string. This text is editable in nature, see the below example.

import java.awt.*;
class TextFieldDemo1{
public static void main(String args[]){
Frame TextF_f= new Frame("studytonight ==>TextField");
TextField text1,text2;
text1=new TextField("Welcome to studytonight");
text1.setBounds(60,100, 230,40);
text2=new TextField("This tutorial is of Java");
text2.setBounds(60,150, 230,40);
TextF_f.add(text1);
TextF_f.add(text2);
TextF_f.setSize(500,500);
TextF_f.setLayout(null);
TextF_f.setVisible(true);
}
}

AWT TextArea
In Java, AWT contains aTextArea Class. It is used for displaying multiple-line text.
TextArea Declaration:
public class TextArea extends TextComponent
Example:
In this example, we are creating a TextArea that is used to display multiple-line text string and allows text editing as well.

import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame textArea_f= new Frame();
3
TextArea area=new TextArea("Welcome to studytonight.com");
area.setBounds(30,40, 200,200);
textArea_f.add(area);
textArea_f.setSize(300,300);
textArea_f.setLayout(null);
textArea_f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
}
}

AWT Checkbox
In Java, AWT contains a Checkbox Class. It is used when we want to select only one option i.e true or false. When the checkbox
is checked then its state is "on" (true) else it is "off"(false).
Checkbox Syntax
public class Checkbox extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating checkbox that are used to get user input. If checkbox is checked it returns true else returns
false.

import java.awt.*;
public class CheckboxDemo1
{
CheckboxDemo1(){
Frame checkB_f= new Frame("studytonight ==>Checkbox Example");
Checkbox ckbox1 = new Checkbox("Yes", true);
ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize(400,400);
checkB_f.setLayout(null);
checkB_f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxDemo1();
}
}

AWT CheckboxGroup
In Java, AWT contains aCheckboxGroup Class. It is used to group a set of Checkbox. When Checkboxes are grouped then only
one box can be checked at a time.
CheckboxGroup Declaration:
public class CheckboxGroup extends Object implements Serializable
Example:
This example creates a checkboxgroup that is used to group multiple checkbox in a single unit. It is helpful when we have to
select single choice among the multiples.

import java.awt.*;
public class CheckboxGroupDemo
{
CheckboxGroupDemo(){
Frame ck_groupf= new Frame("studytonight ==>CheckboxGroup");
4
CheckboxGroupobj = new CheckboxGroup();
Checkbox ckBox1 = new Checkbox("Yes", obj, true);
ckBox1.setBounds(100,100, 50,50);
Checkbox ckBox2 = new Checkbox("No", obj, false);
ckBox2.setBounds(100,150, 50,50);
ck_groupf.add(ckBox1);
ck_groupf.add(ckBox2);
ck_groupf.setSize(400,400);
ck_groupf.setLayout(null);
ck_groupf.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupDemo();
}
}

AWT Choice
In Java, AWT contains a Choice Class. It is used for creating a drop-down menu of choices. When a user selects a particular item
from the drop-down then it is shown on the top of the menu.
Choice Declaration:
public class Choice extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating drop-down menu that is used to get user choice from multiple choices.

import java.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
Frame choice_f= new Frame();
Choice obj=new Choice();
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
choice_f.add(obj);
choice_f.setSize(400,400);
choice_f.setLayout(null);
choice_f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceDemo();
}
}

AWT List
In Java, AWT contains a List Class. It is used to represent a list of items together. One or more than one item can be selected
from the list.
List Declaration:
public class List extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating a list that is used to list out the items.
5
import java.awt.*;
public class ListDemo
{
ListDemo()
{
Frame list_f= new Frame();
List obj=new List(6);
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
list_f.add(obj);
list_f.setSize(400,400);
list_f.setLayout(null);
list_f.setVisible(true);
}
public static void main(String args[])
{
new ListDemo();
}
}

AWT Canvas
In Java, AWT contains a Canvas Class. A blank rectangular area is provided. It is used when a user wants to draw on the screen.
Declaration:
public class Canvas extends Component implements Accessible
Example:
The canvas is used to provide a place to draw using mouse pointer. We can used it to get user architectural user input.

import java.awt.*;
public class CanvasDemo1
{
public CanvasDemo1()
{
Frame canvas_f= new Frame("studytonight ==> Canvas");
canvas_f.add(new CanvasDemo());
canvas_f.setLayout(null);
canvas_f.setSize(500, 500);
canvas_f.setVisible(true);
}
public static void main(String args[])
{
new CanvasDemo1();
}
}
class CanvasDemo extends Canvas
{
public CanvasDemo() {
setBackground (Color.WHITE);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.green);
6
g.fillOval(80, 80, 150, 75);
}
}

What is AWT in Java?


Abstract Window Toolkit acronymed as AWT is a toolkit of classes in Java which helps a programmer to develop Graphics and
Graphical User Interface components. It is a part of JFC (Java Foundation Classes) developed by Sun Microsystems. The AWT API
in Java primarily consists of a comprehensive set of classes and methods that are required for creating and managing the
Graphical User Interface(GUI) in a simplified manner. It was developed for providing a common set of tools for designing the
cross-platform GUIs. One of the important features of AWT is that it is platform dependent. This means that the AWT tools use
the native toolkits of the platforms they are being implemented. This approach helps in preserving the look and feel of each
platform. But as said everything comes with a price, there is a major drawback of this approach. When executed on various
platforms because of platform dependency it will look different on each platform. This hampers the consistency and aesthetics
of an application.
Apart from being platform-dependent, there are several other features of AWT classes about which I will be talking in the next
section of this Java AWT Tutorial.
Features of AWT in Java
AWT is a set of native user interface components
It is based upon a robust event-handling model
It provides Graphics and imaging tools, such as shape, color, and font classes
AWT also avails layout managers which helps in increasing the flexibility of the window layouts
Data transfer classes are also a part of AWT that helps in cut-and-paste through the native platform clipboard
Supports a wide range of libraries that are necessary for creating graphics for gaming products, banking services, educational
purposes, etc.
Now that you are aware of the various features of AWT let me now introduce the aspects of GUI in the next section of this Java
AWT tutorial.
AWT UI Aspects
Any UI will be made of three entities:
UI elements: These refers to the core visual elements which are visible to the user and used for interacting with the application.
AWT in Java provides a comprehensive list of widely used and common elements.
Layouts: These define how UI elements will be organized on the screen and provide the final look and feel to the GUI.
Behavior: These define the events which should occur when a user interacts with UI elements.
I hope, by now you have a brief idea about AWT and what is its role in any application. In the next section of this Java AWT
Tutorial, I will be throwing some light on the complete AWT hierarchy.
Hierarchy Of AWT

As you
can see in the above diagram, Component is the superclass of all the GUI controls. It is an abstract class which encapsulates all
the attributes of a visual component and represents an object with graphical representation. A component class instance is
basically responsible for the look and feel of the current interface.
7
Below I have shown the general class description of java.awt.Component:

Java Certification Training Course


Instructor-led Sessions
Real-life Case Studies
Assignments
Lifetime Access

1 public abstract class Component


2 extends Object
3 implements ImageObserver, MenuContainer, Serializable{
4 //class body
5 }
AWT Components
Containers
Container in Java AWT is a component that is used to hold other components such as text fields, buttons, etc. It is a subclass of
java.awt.Component and is responsible for keeping a track of components being added. There are four types of containers
provided by AWT in Java.
Types of Containers
Window: It is an instance of the Window class having neither border nor title. It is used for creating a top-level window.
Frame: Frame is a subclass of Window and contains title, border and menu bars. It comes with a resizing canvas and is the most
widely used container for developing AWT applications. It is capable of holding various components such as buttons, text fields,
scrollbars, etc. You can create a Java AWT Frame in two ways:
By Instantiating Frame class
By extending Frame class
Dialog: Dialog class is also a subclass of Window and comes with the border as well as the title. Dialog class’s instance always
needs an associated Frame class instance to exist.
Panel: Panel is the concrete subclass of Container and doesn’t contain any title bar, menu bar or border. Panel class is a generic
container for holding the GUI components. You need the instance of the Panel class in order to add the components.
That was all about the container and its types let us now move further in this Java AWT Tutorial article and learn about the rest
of the components.
Button
java.awt.Button class is used to create a labeled button. GUI component that triggers a certain programmed action upon
clicking it. The Button class has two constructors:
1 //Construct a Button with the given label
2 public Button(String btnLabel);
3
4 //Construct a Button with empty label
5 public Button();
A few of the methods provided by this class have been listed below:
1 //Get the label of this Button instance
2 public String getLabel();
3
4 //Set the label of this Button instance
5 public void setLabel(String btnLabel);
6
7 //Enable or disable this Button. Disabled Button cannot be clicked
8 public void setEnable(boolean enable);
Text Field

8
A java.awt.TextField class creates a single-line text box for users to enter texts. The TextField class has three constructors which
are:
1 //Construct a TextField instance with the given initial text string with the number of columns.
2 public TextField(String initialText, int columns);
3
4 //Construct a TextField instance with the given initial text string.
5 public TextField(String initialText);
6
7 //Construct a TextField instance with the number of columns.
8 public TextField(int columns);
A few of the methods provided by TextField class are:
1 // Get the current text on this TextField instance
2 public String getText();
3
4 // Set the display text on this TextField instance
5 public void setText(String strText);
6 //Set this TextField to editable (read/write) or non-editable (read-only)
7 public void setEditable(boolean editable);
Label
The java.awt.Label class provides a descriptive text string that is visible on GUI. An AWT Label object is a component for placing
text in a container. Label class has three constructors which are:
1 // Construct a Label with the given text String, of the text alignment
2 public Label(String strLabel, int alignment);
3
4 //Construct a Label with the given text String
5 public Label(String strLabel);
6
7 //Construct an initially empty Label
8 public Label();
This class also provides 3 constants which are:
1 public static final LEFT; // Label.LEFT
2
3 public static final RIGHT; // Label.RIGHT
4
5 public static final CENTER; // Label.CENTER
Below I have listed down the public methods provided by this class:
1 public String getText();
2
3 public void setText(String strLabel);
4
5 public int getAlignment();
6
7 //Label.LEFT, Label.RIGHT, Label.CENTER
8 public void setAlignment(int alignment);
Programming & Frameworks Training
Canvas
A Canvas class represents the rectangular area where you can draw in an application or receive inputs created by the user.
Choice
Choice class is used to represent a pop-up menu of choices. The selected choice is shown on the top of the given menu.
Scroll Bar
The Scrollbar class object is used to add horizontal and vertical scrollbar in the GUI. It enables a user to see the invisible number
of rows and columns.
List
The object of List class represents a list of text items. Using the List class a user can choose either one item or multiple items.
CheckBox
The Checkbox is a class is a graphical component that is used to create a checkbox. It has two state options; true and false. At
any point in time, it can have either of the two.
So, that was all you need to know about the AWT components. Now, I hope you are ready to get your feet wet with Java AWT
application.
9
In the next section of this Java AWT tutorial, I will show you how to build a calculator using AWT components.
Developing a Calculator with Java AWT
Here I will show you how to create a calculator using AWT, where you will be able to perform basic mathematical operations.
Below is a screenshot of how your Calculator will look like:
Now in order to build this, you need to type in the following code:
1 package edureka.awt;
2
3 import java.awt.*;
4 import java.awt.event.ActionEvent;
5 import java.awt.event.ActionListener;
6
7 class Calculator extends Frame implements ActionListener
8
9 {
10 Label lb1,lb2,lb3;
11
12 TextField txt1,txt2,txt3;
13
14 Button btn1,btn2,btn3,btn4,btn5,btn6,btn7;
15
16 public Calculator()
17 {
18 lb1 = new Label("Var 1");
19 lb2 = new Label("Var 2");
20 lb3 = new Label("Result");
21
22 txt1 = new TextField(10);
23 txt2 = new TextField(10);
24 txt3 = new TextField(10);
25
26 btn1 = new Button("Add");
27 btn2 = new Button("Sub");
28 btn3 = new Button("Multi");
29 btn4 = new Button("Div");
30 btn5 = new Button("Mod");
31 btn6 = new Button("Reset");
32 btn7 = new Button("Close");
33
34 add(lb1);
35 add(txt1);
36 add(lb2);
37 add(txt2);
38 add(lb3);
39 add(txt3);
40 add(btn1);
41 add(btn2);
42 add(btn3);
43 add(btn4);
44 add(btn5);
45 add(btn6);
46 add(btn7);
47
48 setSize(200,200);
49 setTitle("Calculator");
50 setLayout(new FlowLayout());
51 //setLayout(new FlowLayout(FlowLayout.RIGHT));
52 //setLayout(new FlowLayout(FlowLayout.LEFT));
53 btn1.addActionListener(this);
54 btn2.addActionListener(this);
10
55 btn3.addActionListener(this);
56 btn4.addActionListener(this);
57 btn5.addActionListener(this);
58 btn6.addActionListener(this);
59 btn7.addActionListener(this);
60
61 }
62 public void actionPerformed(ActionEvent ae) {
63 double a=0,b=0,c=0;
64 try
65 {
66 a = Double.parseDouble(txt1.getText());
67 }
68 catch (NumberFormatException e) {
69 txt1.setText("Invalid input");
70 }
71 try
72 {
73 b = Double.parseDouble(txt2.getText());
74 }
75 catch (NumberFormatException e) {
76 txt2.setText("Invalid input");
77 }
78 if(ae.getSource()==btn1)
79 {
80 c = a + b;
81 txt3.setText(String.valueOf(c));
82 }
83 if(ae.getSource()==btn2)
84 {
85 c = a - b;
86 txt3.setText(String.valueOf(c));
87 }
88 if(ae.getSource()==btn3)
89 {
90 c = a * b;
91 txt3.setText(String.valueOf(c));
92 }
93 if(ae.getSource()==btn4)
94 {
95 c = a / b;
96 txt3.setText(String.valueOf(c));
97 }
98 if(ae.getSource()==btn5)
99 {
100 c = a % b;
101 txt3.setText(String.valueOf(c));
102 }
103 if(ae.getSource()==btn6)
104 {
105 txt1.setText("0");
106 txt2.setText("0");
107 txt3.setText("0");
108 }
109 if(ae.getSource()==btn7)
110 {
111 System.exit(0);
112 }
113 }
11
114 public static void main(String[] args)
115 {
116 Calculator calC = new Calculator();
117 calC.setVisible(true);
118 calC.setLocation(300,300);
119 }
120 }
As you might have noticed that here we have used just functionalities. You can always add more functions to your application
and create a full-fledged Calculator.

Java AWT tutorial for beginners


By Chaitanya Singh | Filed Under: java
AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating Graphical User Interface (GUI) for java
programs.
Why AWT is platform dependent? Java AWT calls native platform (Operating systems) subroutine for creating components such as
textbox, checkbox, button etc. For example an AWT GUI having a button would have a different look and feel across platforms like
windows, Mac OS & Unix, this is because these platforms have different look and feel for their native buttons and AWT directly calls
their native subroutine that creates the button. In simple, an application build on AWT would look like a windows application when
it runs on Windows, but the same application would look like a Mac application when runs on Mac OS.
AWT is rarely used now days because of its platform dependent and heavy-weight nature. AWT components are considered heavy
weight because they are being generated by underlying operating system (OS). For example if you are instantiating a text box in
AWT that means you are actually asking OS to create a text box for you.
Swing is a preferred API for window based applications because of its platform independent and light-weight nature. Swing is built
upon AWT API however it provides a look and feel unrelated to the underlying platform. It has more powerful and flexible
components than AWT. In addition to familiar components such as buttons, check boxes and labels, Swing provides several
advanced components such as tabbed panel, scroll panes, trees, tables, and lists. We will discuss Swing in detail in a separate
tutorial.
AWT hierarchy

Components and containers


All the elements like buttons, text fields, scrollbars etc are known as components. In AWT we have classes for each component as
shown in the above diagram. To have everything placed on a screen to a particular position, we have to add them to a container. A
container is like a screen wherein we are placing components like buttons, text fields, checkbox etc. In short a container contains
and controls the layout of components. A container itself is a component (shown in the above hierarchy diagram) thus we can add a
container inside container.
Types of containers:
As explained above, a container is a place wherein we add components like text field, button, checkbox etc. There are four types of
containers available in AWT: Window, Frame, Dialog and Panel. As shown in the hierarchy diagram above, Frame and Dialog are
subclasses of Window class.
Window: An instance of the Window class has no border and no title
Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist without an associated instance of the Frame
class.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for holding components. An instance of the
12
Panel class provides a container to which to add components.
Frame: A frame has title, border and menu bars. It can contain several components like buttons, text fields, scrollbars etc. This is
most widely used container while developing an application in AWT.
Java AWT Example
We can create a GUI using Frame in two ways:
1) By extending Frame class
2) By creating the instance of Frame class
Lets have a look at the example of each one.
AWT Example 1: creating Frame by extending Frame class
import java.awt.*;
/* We have extended the Frame class here,
* thus our class "SimpleExample" would behave
* like a Frame
*/
public class SimpleExample extends Frame{
SimpleExample(){
Button b=new Button("Button!!");

// setting button position on screen


b.setBounds(50,50,50,50);

//adding button into frame


add(b);

//Setting Frame width and height


setSize(500,300);

//Setting the title of Frame


setTitle("This is my First AWT example");

//Setting the layout for the Frame


setLayout(new FlowLayout());

/* By default frame is not visible so


* we are setting the visibility to true
* to make it visible.
*/
setVisible(true);
}
public static void main(String args[]){
// Creating the instance of Frame
SimpleExample fr=new SimpleExample();
}
}
Output:

AWT Example 2: creating Frame by creating instance of Frame class


import java.awt.*;
public class Example2 {
Example2()
{
//Creating Frame
Frame fr=new Frame();

//Creating a label
Label lb = new Label("UserId: ");

//adding label to the frame

13
fr.add(lb);

//Creating Text Field


TextField t = new TextField();

//adding text field to the frame


fr.add(t);

//setting frame size


fr.setSize(500, 300);

//Setting the layout for the Frame


fr.setLayout(new FlowLayout());

fr.setVisible(true);
}
public static void main(String args[])
{
Example2 ex = new Example2();
}
}
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.applet.*;
/*
<applet code = "LabelDemo" width=300 height=200>
14
</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:

15
AWR 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
{
16
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);
17
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 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);
18
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
19
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;
20
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.

21
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
22
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);
23
}
}
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.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

24

You might also like