[go: up one dir, main page]

0% found this document useful (0 votes)
282 views25 pages

Window Panel Frame Dialog: Types of Containers

The document discusses Java AWT containers and components. It describes the four main container types in AWT - Window, Panel, Frame, and Dialog. It also provides examples of creating AWT applications using Frame containers with buttons, text fields, and labels. The document also covers Java event handling and lists common event classes and listener interfaces. It provides examples of adding action listeners to buttons and updating text fields in response to button clicks.

Uploaded by

James Bond
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)
282 views25 pages

Window Panel Frame Dialog: Types of Containers

The document discusses Java AWT containers and components. It describes the four main container types in AWT - Window, Panel, Frame, and Dialog. It also provides examples of creating AWT applications using Frame containers with buttons, text fields, and labels. The document also covers Java event handling and lists common event classes and listener interfaces. It provides examples of adding action listeners to buttons and updating text fields in response to button clicks.

Uploaded by

James Bond
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/ 25

22 March 2022 12:20

Types of containers:
There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog
Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window. We need to create an
instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is
generic container for holding the components. It can have other components like
button, text field etc. An instance of Panel class creates a container, in which we
can add components.
Frame
The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame is
most widely used container while developing an AWT application.
Useful Methods of Component Class
Method Description
public void add(Component c) Inserts a component on this component.
public void setSize(int width,int Sets the size (width and height) of the
height) component.
public void Defines the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean Changes the visibility of the component, by
status) default false.
Java AWT Example
To create simple AWT example, you need a frame. There are two ways to
create a GUI using Frame in AWT.
By extending Frame class (inheritance)
By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here,
we are showing Button component on the Frame.
AWTExample1.java
import java.awt.*;

awt Page 1
public class AWTExample1 extends Frame {

AWTExample1() {
Button b = new Button("Click Me!!");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setTitle("This is our basic AWT example");
setLayout(null);
setVisible(true);
}

public static void main(String args[]) {

AWTExample1 f = new AWTExample1();

}
Output:

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame
class. Here, we are creating a TextField, Label and Button component on the
Frame.
AWTExample2.java
import java.awt.*;
class AWTExample2 {
AWTExample2() {
Frame f = new Frame();
Label l = new Label("Employee id:");
Button b = new Button("Submit");
TextField t = new TextField();

l.setBounds(20, 80, 80, 30);

awt Page 2
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);

f.add(b);
f.add(l);
f.add(t);

f.setSize(400,300);

f.setTitle("Employee info");

f.setLayout(null);

f.setVisible(true);
}

public static void main(String args[]) {

AWTExample2 awt_obj = new AWTExample2();

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on
button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:

awt Page 3
Following steps are required to perform event handling:
Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:
Within class
Other class
Anonymous class
Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

awt Page 4
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been
used in the above example that sets the position of the component it may be
button, textfield etc.

2) Java event handling by outer class


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

class AEvent2 extends Frame{


TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
awt Page 5
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}

import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}

3) Java event handling by anonymous class


import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);

b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}

awt Page 6
AWT Button Class Declaration
public class Button extends Component implements Accessible
Button Class Constructors
Following table shows the types of Button class constructors
Sr. no. Constructor Description
1. Button( ) It constructs a new button with an empty string i.e. it has
no label.
2. Button (String It constructs a new button with given string as its label.
text)

Button Class Methods


Sr. no. Method Description
1. void setText (String text) It sets the string message on the button
2. String getText() It fetches the String message on the button.
3. void setLabel (String It sets the label of button with the specified
label) string.
4. String getLabel() It fetches the label of the button.
5. void addNotify() It creates the peer of the button.
6. AccessibleContext It fetched the accessible context associated with
getAccessibleContext() the button.
7. void It adds the specified action listener to get the
addActionListener(ActionL action events from the button.
istener l)
8. String It returns the command name of the action
getActionCommand() event fired by the button.
9. ActionListener[ ] It returns an array of all the action listeners
getActionListeners() registered on the button.
10. T[ ] It returns an array of all the objects currently
getListeners(Class listener registered as FooListeners upon this Button.
Type)
11. protected String It returns the string which represents the state
paramString() of button.
12. protected void It process the action events on the button by
processActionEvent dispatching them to a registered ActionListener
(ActionEvent e) object.
13. protected void It process the events on the button
processEvent (AWTEvent
e)
14. void removeActionListener It removes the specified action listener so that it
(ActionListener l) no longer receives action events from the
button.
15. void It sets the command name for the action event
setActionCommand(String given by the button.
command)
Note: The Button class inherits methods from java.awt.Component and java.lang.Object classes.
Java AWT Button Example
Example 1:
ButtonExample.java
awt Page 7
ButtonExample.java
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {

// create instance of frame with the label


Frame f = new Frame("Button Example");

// create instance of button with label


Button b = new Button("Click Here");

// set the position for the button in frame


b.setBounds(50,100,80,30);

// add button to the frame


f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
To compile the program using command prompt type the following commands
C:\Users\Anurati\Desktop\abcDemo>javac ButtonExample.java
If there's no error, we can execute the code using:
C:\Users\Anurati\Desktop\abcDemo>java ButtonExample
Output:

Example 2:
// importing necessary libraries
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ButtonExample2


{
// creating instances of Frame class and Button class
Frame fObj;
Button button1, button2, button3;
// instantiating using the constructor
ButtonExample2() {
fObj = new Frame ("Frame to display buttons");
button1 = new Button();

awt Page 8
button1 = new Button();
button2 = new Button ("Click here");
button3 = new Button();
button3.setLabel("Button 3");
fObj.add(button1);
fObj.add(button2);
fObj.add(button3);
fObj.setLayout(new FlowLayout());
fObj.setSize(300,400);
fObj.setVisible(true);
}
// main method
public static void main (String args[])
{
new ButtonExample2();
}
}
Output:

Java AWT Button Example with ActionListener


Example:
In the following example, we are handling the button click events by implementing
ActionListener Interface.
ButtonExample3.java
// importing necessary libraries
import java.awt.*;
import java.awt.event.*;
public class ButtonExample3 {
public static void main(String[] args) {
// create instance of frame with the label
Frame f = new Frame("Button Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
// create instance of button with label
Button b=new Button("Click Here");

awt Page 9
Button b=new Button("Click Here");
// set the position for the button in frame
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
tf.setText("Welcome to Javatpoint.");
}
});
// adding button the frame
f.add(b);
// adding textfield the frame
f.add(tf);
// setting size, layout and visibility
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

AWT Label Fields


The java.awt.Component class has following fields:
static int LEFT: It specifies that the label should be left justified.
static int RIGHT: It specifies that the label should be right justified.
static int CENTER: It specifies that the label should be placed in center.
Label class Constructors
Sr. no. Constructor Description
1. Label() It constructs an empty label.
2. Label(String text) It constructs a label with the given string (left
justified by default).
3. Label(String text, int It constructs a label with the specified string and
alignement) the specified alignment.

Label Class Methods


Specified
Sr. no. Method name Description
1. void setText(String text) It sets the texts for label with the specified
text.
2. void setAlignment(int It sets the alignment for label with the
alignment) specified alignment.

awt Page 10
alignment) specified alignment.
3. String getText() It gets the text of the label
4. int getAlignment() It gets the current alignment of the label.
5. void addNotify() It creates the peer for the label.
6. AccessibleContext It gets the Accessible Context associated
getAccessibleContext() with the label.
7. protected String paramString() It returns the string the state of the label.

Method inherited
The above methods are inherited by the following classes:
java.awt.Component
java.lang.Object
Java AWT Label Example
In the following example, we are creating two labels l1 and l2 using the Label(String
text) constructor and adding them into the frame.
LabelExample.java
import java.awt.*;

public class LabelExample {


public static void main(String args[]){

// creating the object of Frame class and Label class


Frame f = new Frame ("Label example");
Label l1, l2;

// initializing the labels


l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");

// set the location of label


l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);

// adding labels to the frame


f.add(l1);
f.add(l2);

// setting size, layout and visibility of frame


f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

awt Page 11
Java AWT Label Example with ActionListener
In the following example, we are creating the objects of TextField, Label
and Button classes and adding them to the Frame. Using the actionPerformed()
method an event is generated over the button. When we add the website in the text
field and click on the button, we get the IP address of website.
LabelExample2.java
import java.awt.*;
import java.awt.event.*;

// creating class which implements ActionListener interface and inherits Frame class

public class LabelExample2 extends Frame implements ActionListener{

// creating objects of TextField, Label and Button class


TextField tf;
Label l;
Button b;

// constructor to instantiate the above objects


LabelExample2() {
tf = new TextField();
tf.setBounds(50, 50, 150, 20);

l = new Label();
l.setBounds(50, 100, 250, 20);

b = new Button("Find IP");


b.setBounds(50,150,60,30);
b.addActionListener(this);

add(b);
add(tf);
add(l);

setSize(400,400);
setLayout(null);
setVisible(true);
}

// defining actionPerformed method to generate an event


public void actionPerformed(ActionEvent e) {
try {
String host = tf.getText();

awt Page 12
String host = tf.getText();
String ip = java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}
catch (Exception ex) {
System.out.println(ex);
}
}

// main method
public static void main(String[] args) {
new LabelExample2();
}
}
Output:

Java AWT TextField


The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further
inherits Component class.
When we enter a key in the text field (like key pressed, key released or key typed),
the event is sent to TextField. Then the KeyEvent is passed to the
registered KeyListener. It can also be done using ActionEvent; if the ActionEvent is
enabled on the text field, then the ActionEvent may be fired by pressing return key.
The event is handled by the ActionListener interface.
AWT TextField Class Declaration
public class TextField extends TextComponent
TextField Class constructors
Sr. no. Constructor Description
1. TextField() It constructs a new text field component.
2. TextField(String text) It constructs a new text field initialized with the given
string text to be displayed.
3. TextField(int columns) It constructs a new textfield (empty) with given
number of columns.
4. TextField(String text, It constructs a new text field with the given text and
int columns) given number of columns (width).

TextField Class Methods


Sr. no. Method name Description

awt Page 13
1. void addNotify() It creates the peer of text field.
2. boolean echoCharIsSet() It tells whether text field has character set for
echoing or not.
3. void It adds the specified action listener to receive
addActionListener(Action action events from the text field.
Listener l)
4. ActionListener[] It returns array of all action listeners registered on
getActionListeners() text field.
5. AccessibleContext It fetches the accessible context related to the
getAccessibleContext() text field.
6. int getColumns() It fetches the number of columns in text field.
7. char getEchoChar() It fetches the character that is used for echoing.
8. Dimension It fetches the minimum dimensions for the text
getMinimumSize() field.
9. Dimension It fetches the minimum dimensions for the text
getMinimumSize(int field with specified number of columns.
columns)
10. Dimension It fetches the preferred size of the text field.
getPreferredSize()
11. Dimension It fetches the preferred size of the text field with
getPreferredSize(int specified number of columns.
columns)
12. protected String It returns a string representing state of the text
paramString() field.
13. protected void It processes action events occurring in the text
processActionEvent(Acti field by dispatching them to a registered
onEvent e) ActionListener object.
14. protected void It processes the event on text field.
processEvent(AWTEven
t e)
15. void It removes specified action listener so that it
removeActionListener(A doesn't receive action events anymore.
ctionListener l)
16. void setColumns(int It sets the number of columns in text field.
columns)
17. void setEchoChar(char It sets the echo character for text field.
c)
18. void setText(String t) It sets the text presented by this text component
to the specified text.

Method Inherited
The AWT TextField class inherits the methods from below classes:
java.awt.TextComponent
java.awt.Component
java.lang.Object
Java AWT TextField Example
TextFieldExample1.java
// importing AWT class
import java.awt.*;

awt Page 14
import java.awt.*;
public class TextFieldExample1 {
// main method
public static void main(String args[]) {
// creating a frame
Frame f = new Frame("TextField Example");

// creating objects of textfield


TextField t1, t2;
// instantiating the textfield objects
// setting the location of those objects in the frame
t1 = new TextField("Welcome to Javatpoint.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
// adding the components to frame
f.add(t1);
f.add(t2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

Java AWT TextField Example with ActionListener


TextFieldExample2.java
// importing necessary libraries
import java.awt.*;
import java.awt.event.*;
// Our class extends Frame class and implements ActionListener interface
public class TextFieldExample2 extends Frame implements ActionListener {
// creating instances of TextField and Button class
TextField tf1, tf2, tf3;
Button b1, b2;
// instantiating using constructor
TextFieldExample2() {
// instantiating objects of text field and button
// setting position of components in frame
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);

awt Page 15
tf1.setBounds(50, 50, 150, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);
b1 = new Button("+");
b1.setBounds(50, 200, 50, 50);
b2 = new Button("-");
b2.setBounds(120,200,50,50);
// adding action listener
b1.addActionListener(this);
b2.addActionListener(this);
// adding components to frame
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
// setting size, layout and visibility of frame
setSize(300,300);
setLayout(null);
setVisible(true);
}
// defining the actionPerformed method to generate an event on buttons
public void actionPerformed(ActionEvent e) {
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0;
if (e.getSource() == b1){
c = a + b;
}
else if (e.getSource() == b2){
c = a - b;
}
String result = String.valueOf(c);
tf3.setText(result);
}
// main method
public static void main(String[] args) {
new TextFieldExample2();
}
}
Output:

awt Page 16
Java AWT TextArea
The object of a TextArea class is a multiline region that displays text. It allows the
editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the text
area becomes larger than the viewable area, the scroll bar appears automatically
which helps us to scroll the text up and down, or right and left.
AWT TextArea Class Declaration
public class TextArea extends TextComponent
Fields of TextArea Class
The fields of java.awt.TextArea class are as follows:
static int SCROLLBARS_BOTH - It creates and displays both horizontal and
vertical scrollbars.
static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only
the horizontal scrollbar.
static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the
vertical scrollbar.
static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in
the text area.
Class constructors:
Sr. no. Constructor Description
1. TextArea() It constructs a new and empty text area with no
text in it.
2. TextArea (int row, int It constructs a new text area with specified
column) number of rows and columns and empty string
as text.
3. TextArea (String text) It constructs a new text area and displays the
specified text in it.
4. TextArea (String text, int It constructs a new text area with the specified
row, int column) text in the text area and specified number of
rows and columns.
5. TextArea (String text, int It construcst a new text area with specified text in
row, int column, int text area and specified number of rows and
awt Page 17
row, int column, int text area and specified number of rows and
scrollbars) columns and visibility.
Methods Inherited
The methods of TextArea class are inherited from following classes:
40.7M
847
Exception Handling in Java - Javatpoint

java.awt.TextComponent
java.awt.Component
java.lang.Object
TetArea Class Methods
Sr. no. Method name Description
1. void addNotify() It creates a peer of text area.
2. void append(String str) It appends the specified text to the current text
of text area.
3. AccessibleContext It returns the accessible context related to the
getAccessibleContext() text area
4. int getColumns() It returns the number of columns of text area.
5. Dimension It determines the minimum size of a text area.
getMinimumSize()
6. Dimension It determines the minimum size of a text area
getMinimumSize(int rows, with the given number of rows and columns.
int columns)
7. Dimension It determines the preferred size of a text area.
getPreferredSize()
8. Dimension It determines the preferred size of a text area
preferredSize(int rows, int with given number of rows and columns.
columns)
9. int getRows() It returns the number of rows of text area.
10. int getScrollbarVisibility() It returns an enumerated value that indicates
which scroll bars the text area uses.
11. void insert(String str, int It inserts the specified text at the specified
pos) position in this text area.
12. protected String It returns a string representing the state of this
paramString() TextArea.
13. void replaceRange(String It replaces text between the indicated start and
str, int start, int end) end positions with the specified replacement
text.
14. void setColumns(int It sets the number of columns for this text area.
columns)
15. void setRows(int rows) It sets the number of rows for this text area.
Java AWT TextArea Example
The below example illustrates the simple implementation of TextArea where we are
creating a text area using the constructor TextArea(String text) and adding it to the
frame.
TextAreaExample .java
//importing AWT class
import java.awt.*;
public class TextAreaExample

awt Page 18
public class TextAreaExample
{
// constructor to initialize
TextAreaExample() {
// creating a frame
Frame f = new Frame();
// creating a text area
TextArea area = new TextArea("Welcome to javatpoint");
// setting location of text area in frame
area.setBounds(10, 30, 300, 300);
// adding text area to frame
f.add(area);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new TextAreaExample();
}
}
Output:

Java AWT TextArea Example with ActionListener


The following example displays a text area in the frame where it extends the Frame
class and implements ActionListener interface. Using ActionListener the event is
generated on the button press, where we are counting the number of character and
words entered in the text area.
TextAreaExample2.java
// importing necessary libraries
import java.awt.*;
import java.awt.event.*;
// our class extends the Frame class to inherit its properties
// and implements ActionListener interface to override its methods
public class TextAreaExample2 extends Frame implements ActionListener {
awt Page 19
public class TextAreaExample2 extends Frame implements ActionListener {
// creating objects of Label, TextArea and Button class.
Label l1, l2;
TextArea area;
Button b;
// constructor to instantiate
TextAreaExample2() {
// instantiating and setting the location of components on the frame
l1 = new Label();
l1.setBounds(50, 50, 100, 30);
l2 = new Label();
l2.setBounds(160, 50, 100, 30);
area = new TextArea();
area.setBounds(20, 100, 300, 300);
b = new Button("Count Words");
b.setBounds(100, 400, 100, 30);

// adding ActionListener to button


b.addActionListener(this);

// adding components to frame


add(l1);
add(l2);
add(area);
add(b);
// setting the size, layout and visibility of frame
setSize(400, 450);
setLayout(null);
setVisible(true);
}
// generating event text area to count number of words and characters
public void actionPerformed(ActionEvent e) {
String text = area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
// main method
public static void main(String[] args) {
new TextAreaExample2();
}
}
Output:

awt Page 20
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on
(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or
from "off" to "on".
AWT Checkbox Class Declaration
public class Checkbox extends Component implements ItemSelectable, Accessibl
e
Checkbox Class Constructors
Sr. no. Constructor Description
1. Checkbox() It constructs a checkbox with no string as the
label.
2. Checkbox(String label) It constructs a checkbox with the given label.
3. Checkbox(String label, It constructs a checkbox with the given label
boolean state) and sets the given state.
4. Checkbox(String label, It constructs a checkbox with the given label,
boolean state, set the given state in the specified checkbox
CheckboxGroup group) group.
5. Checkbox(String label, It constructs a checkbox with the given label,
CheckboxGroup group, in the given checkbox group and set to the
boolean state) specified state.
Method inherited by Checkbox
The methods of Checkbox class are inherited by following classes:
java.awt.Component
java.lang.Object
Checkbox Class Methods
awt Page 21
Checkbox Class Methods
Sr. no. Method name Description
1. void It adds the given item listener to get the item events
addItemListener(ItemL from the checkbox.
istener IL)
2. AccessibleContext It fetches the accessible context of checkbox.
getAccessibleContext(
)
3. void addNotify() It creates the peer of checkbox.
4. CheckboxGroup It determines the group of checkbox.
getCheckboxGroup()
5. ItemListener[] It returns an array of the item listeners registered on
getItemListeners() checkbox.
6. String getLabel() It fetched the label of checkbox.
7. T[] It returns an array of all the objects registered as
getListeners(Class list FooListeners.
enerType)
8. Object[] It returns an array (size 1) containing checkbox
getSelectedObjects() label and returns null if checkbox is not selected.
9. boolean getState() It returns true if the checkbox is on, else returns off.
10. protected String It returns a string representing the state of
paramString() checkbox.
11. protected void It processes the event on checkbox.
processEvent(AWTEv
ent e)
12. protected void It process the item events occurring in the
processItemEvent(Ite checkbox by dispatching them to registered
mEvent e) ItemListener object.
13. void It removes the specified item listener so that the
removeItemListener(It item listener doesn't receive item events from the
emListener l) checkbox anymore.
14. void It sets the checkbox's group to the given checkbox.
setCheckboxGroup(Ch
eckboxGroup g)
15. void setLabel(String It sets the checkbox's label to the string argument.
label)
16. void setState(boolean It sets the state of checkbox to the specified state.
state)

Java AWT Checkbox Example


In the following example we are creating two checkboxes using the Checkbox(String
label) constructo and adding them into the Frame using add() method.
CheckboxExample1.java
// importing AWT class
import java.awt.*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");

awt Page 22
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
checkbox2.setBounds(100, 150, 50, 50);
// adding checkboxes to frame
f.add(checkbox1);
f.add(checkbox2);

// setting size, layout and visibility of frame


f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main (String args[])
{
new CheckboxExample1();
}
}
Output:

Java AWT Checkbox Example with ItemListener


In the following example, we have created two checkboxes and adding them into the
Frame. Here, we are adding the ItemListener with the checkbox which displays the
state of the checkbox (whether it is checked or unchecked) using the
getStateChange() method.
CheckboxExample2.java
// importing necessary packages
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample2
{
// constructor to initialize
CheckboxExample2() {
// creating the frame
Frame f = new Frame ("CheckBox Example");
// creating the label
final Label label = new Label();
// setting the alignment, size of label
label.setAlignment(Label.CENTER);

awt Page 23
label.setAlignment(Label.CENTER);
label.setSize(400,100);
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100, 150, 50, 50);
// adding the checkbox to frame
f.add(checkbox1);
f.add(checkbox2);
f.add(label);

// adding event to the checkboxes


checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new CheckboxExample2();
}
}
Output:

awt Page 24
awt Page 25

You might also like