AWT Controls in Java With Examples
AWT Controls in Java With Examples
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.
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.
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.
public CanvasDemo ()
{
prepareGUI ();
}
mainFrame.add (headerLabel);
mainFrame.add (controlPanel);
mainFrame.add (statusLabel);
mainFrame.setVisible (true);
}
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)
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 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());
Output:
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.
package javaapplication22;
import java.awt.*;
import java.awt.event.*;
public JavaApplication22() {
setTitle("Radio Button Demo");
setSize(250, 200);
setLayout(new FlowLayout());
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
Output:
public Main() {
setTitle("Choice Demo");
setSize(300, 180);
setLayout(new FlowLayout());
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.
public Main()
{
setTitle("List Demo");
setBackground(Color.yellow);
setSize(300, 180);
setLayout(new FlowLayout());
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.
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);
// Register listeners
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
1. TextField
2. TextArea
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.
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:
add(text);