0% found this document useful (0 votes)
76 views50 pages

Unit-Iv Awt Notes

Uploaded by

pearl
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)
76 views50 pages

Unit-Iv Awt Notes

Uploaded by

pearl
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/ 50

CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Syllabus:

The AWT class hierarchy, user interface components- labels, button,


canvas, scrollbars, text components, check box, checkbox groups, choices,

lists panels – scrollpane, dialogs, menubar, graphics, layout manager –


layout manager types – border, grid, flow, card and grid bag

Java AWT:

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User


Interface (GUI) or windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed


according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in
simple and easy steps.

Why AWT is platform independent?

Java AWT calls the native platform calls the native platform (operating
systems) subroutine for creating API components like TextField, ChechBox,
button, etc.

For example, an AWT GUI with components like TextField, label and button
will have different look and feel for the different platforms like Windows, MAC
OS, and Unix. The reason for this is the platforms have different view for their
native components and AWT directly calls the native subroutine that creates
those components.

In simple words, an AWT application will look like a windows application in


Windows OS whereas it will look like a Mac application in the MAC OS.

AWT Classes :

The AWT classes are contained in the java.awt package. It is one of Java’s
largest packages
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below:

Component:

->. All user interface elements that are displayed on the screen and that interact
with the user are subclasses of Component.

->It defines over a hundred public methods that are responsible for managing
events, such as mouse and keyboard input, positioning and sizing the window,
and repainting
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

->A Component object is responsible for remembering the current foreground


and background colors and the currently selected text font

Container :

The Container class is a subclass of Component. It has additional methods that


allow other Component objects to be nested within it. Other Container objects
can be stored inside of a Container (since they are themselves instances of
Component). This makes for a multileveled containment system.

Types of containers:

There are four types of containers in Java AWT:

1. Window
2. Panel
3. Frame
4. Dialog

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 ,

The Panel class is a concrete subclass of Container. It doesn’t add any new
methods; it simply implements Container. A Panel may be thought of as a
recursively nestable, concrete screen component. Panel is the superclass for
Applet.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Other components can be added to a Panel object by its add( ) method (inherited
from Container). Once these components have been added, you can position and
resize them manually using the setLocation( ), setSize( ), setPreferredSize( ), or
setBounds( ) methods defined by Component

Window:

The Window class creates a top-level window. A top-level window is not


contained within any other object; it sits directly on the desktop. Generally, you
won’t create Window objects directly. Instead, you will use a subclass of
Window called Frame, The window is the container that have no borders and
menu bars.

Frame :

Frame encapsulates what is commonly thought of as a “window.” It is a


subclass of Window and has a title bar, menu bar, borders, and resizing corners,
It can have other components like button, text field, scrollbar etc. Frame is most
widely used container while developing an AWT application.

Canvas:

Although it is not part of the hierarchy for applet or frame windows, there is
one other type of window that you will find valuable: Canvas. Canvas
encapsulates a blank window upon which you can draw

Working with Frame Windows:

Here are two of Frame’s constructors:

Frame( )

Frame(String title)

The first form creates a standard window that does not contain a title. The
second form creates a window with the title specified by title.

Setting the Window’s Dimensions

The setSize( ) method is used to set the dimensions of the window. Its signature
is shown here: void setSize(int newWidth, int newHeight)
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

void setSize(Dimension newSize)

The new size of the window is specified by newWidth and newHeight, or by the
width and height fields of the Dimension object passed in newSize. The
dimensions are specified in terms of pixels.

Hiding and Showing a Window :

After a frame window has been created, it will not be visible until you call
setVisible( ). Its signature is shown here: void setVisible(boolean visibleFlag)

Setting a Window’s Title:

You can change the title in a frame window using setTitle( ), which has this
general form: void setTitle(String newTitle)

Frames Creations:

There are two ways to create a GUI using Frame in AWT.

1. By extending Frame class (inheritance)


2. By creating the object of Frame class (association)

By inheritance:

By Association:
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

User interface components:

Label:

The object of the Label class is a component for placing text in a container. It is
used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.

It is called a passive control as it does not create any event when it is accessed.
To create a label, we need to create the object of Label class.

AWT Label Fields

The java.awt.Component class has following fields:

1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.

Label class Constructors

Sr. Constructor Description


no.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

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


alignement) string and the specified alignment.

Label Class Methods

Sr. Method name Description


no.

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


alignment) with the 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


getAccessibleContext() associated with the label.

7. protected String paramString() It returns the string the state of


the label.

Button:

A button is basically a control component with a label that generates an event


when pushed.

To perform an action on a button being pressed and released,


the ActionListener interface needs to be implemented. The registered new
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

listener can receive events from the button by


calling addActionListener method of the button.

Button Class Constructors

Following table shows the types of Button class constructors

Sr. Constructor Description


no.

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


text) as its label.

Button Class Methods

Sr. Method Description


no.

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 label) It sets the label of button


with the specified 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


CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

getAccessibleContext() context associated with the


button.

7. void It adds the specified action


addActionListener(ActionListener l) listener to get the action
events from the button.

8. String getActionCommand() It returns the command


name of the action event
fired by the button.

9. ActionListener[ ] It returns an array of all the


getActionListeners() action listeners registered
on the button.

10. T[ ] getListeners(Class listenerType) It returns an array of all the


objects currently registered
as FooListeners upon this
Button.

11. protected String paramString() It returns the string which


represents the state of
button.

12. protected void processActionEvent It process the action events


(ActionEvent e) on the button by
dispatching them to a
registered ActionListener
object.

13. protected void processEvent It process the events on the


(AWTEvent e) button

14. void removeActionListener It removes the specified


action listener so that it no
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

(ActionListener l) longer receives action


events from the button.

15. void setActionCommand(String It sets the command name


command) for the action event given
by the button.

TextField:

The object of a TextField class is a text component that allows a user to enter a
single line text and edit it.

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

TextField Class constructors

Sr. Constructor Description


no.

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.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

4. TextField(String text, It constructs a new text field with the


int columns) given text and given number of
columns (width).

TextField Class Methods

Sr. Method name Description


no.

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 addActionListener(ActionListener It adds the specified


l) action listener to receive
action events from the
text field.

4. ActionListener[] getActionListeners() It returns array of all


action listeners
registered on text field.

5. AccessibleContext It fetches the accessible


getAccessibleContext() context related to the
text field.

6. int getColumns() It fetches the number of


columns in text field.

7. char getEchoChar() It fetches the character


CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

that is used for echoing.

8. Dimension getMinimumSize() It fetches the minimum


dimensions for the text
field.

9. Dimension getMinimumSize(int It fetches the minimum


columns) dimensions for the text
field with specified
number of columns.

10. Dimension getPreferredSize() It fetches the preferred


size of the text field.

11. Dimension getPreferredSize(int It fetches the preferred


columns) size of the text field with
specified number of
columns.

12. protected String paramString() It returns a string


representing state of the
text field.

13. protected void It processes action


processActionEvent(ActionEvent e) events occurring in the
text field by dispatching
them to a registered
ActionListener object.

14. protected void It processes the event on


processEvent(AWTEvent e) text field.

15. void It removes specified


removeActionListener(ActionListener action listener so that it
doesn't receive action
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

l) events anymore.

16. void setColumns(int columns) It sets the number of


columns in text field.

17. void setEchoChar(char c) It sets the echo character


for text field.

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:

1. java.awt.TextComponent
2. java.awt.Component
3. java.lang.Object

JAVA PROGRAM ILLUSTRATE

ON

Label,Button,TextField with ActionListener , WindowAdpater

Code:

package test1;
import java.awt.*;
import java.awt.event.*;
public class TextFieldExample2 extends Frame implements ActionListener {
TextField tf1, tf2, tf3;
Button b1, b2;
TextFieldExample2() {
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

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);
b1.addActionListener(this);
b2.addActionListener(this);
add(tf1); add(tf2); add(tf3);
add(b1); add(b2);
setSize(300,300); setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}
// 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();
}
}
CMRCET CSE JAVA UNIT IV PART -1 NOTES 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.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Fields of TextArea Class

The fields of java.awt.TextArea class are as follows:

o static int SCROLLBARS_BOTH - It creates and displays both


horizontal and vertical scrollbars.
o static int SCROLLBARS_HORIZONTAL_ONLY - It creates and
displays only the horizontal scrollbar.
o static int SCROLLBARS_VERTICAL_ONLY - It creates and displays
only the vertical scrollbar.
o static int SCROLLBARS_NONE - It doesn't create or display any
scrollbar in the text area.

Class constructors:

Sr. Constructor Description


no.

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


column) specified 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, It constructs a new text area with the


int row, int column) specified text in the text area and
specified number of rows and
columns.

5. TextArea (String text, It construcst a new text area with


int row, int column, int specified text in text area and specified
number of rows and columns and
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

scrollbars) visibility.

Methods Inherited

The methods of TextArea class are inherited from following classes:

o java.awt.TextComponent
o java.awt.Component
o java.lang.Object

TetArea Class Methods

Sr. Method name Description


no.

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


getAccessibleContext() related to the text area

4. int getColumns() It returns the number of columns


of text area.

5. Dimension It determines the minimum size


getMinimumSize() of a text area.

6. Dimension It determines the minimum size


getMinimumSize(int rows, int of a text area with the given
columns) number of rows and columns.

7. Dimension getPreferredSize() It determines the preferred size


of a text area.

8. Dimension preferredSize(int It determines the preferred size


rows, int columns) of a text area with given number
of rows and columns.

9. int getRows() It returns the number of rows of


text area.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

10. int getScrollbarVisibility() It returns an enumerated value


that indicates which scroll bars
the text area uses.

11. void insert(String str, int pos) It inserts the specified text at the
specified position in this text
area.

12. protected String It returns a string representing


paramString() the state of this TextArea.

13. void replaceRange(String str, It replaces text between the


int start, int end) indicated start and end positions
with the specified replacement
text.

14. void setColumns(int columns) It sets the number of columns for


this text area.

15. void setRows(int rows) It sets the number of rows for


this text area.

Java Code on TextArea :


CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Java Code on Text Area with Action listner:

package test1;
import java.awt.*;
import java.awt.event.*;
public class TextAreaExample2 extends Frame implements ActionListener {
Label l1, l2;
TextArea area;
Button b;
TextAreaExample2() {
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);
b.addActionListener(this);
add(l1); add(l2);add(area);
add(b);
setSize(400, 450);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}
//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) {
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

new TextAreaExample2();
}
}

Output:

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

Checkbox Class Constructors

Sr. Constructor Description


no.

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


boolean state) given label and sets the given state.

4. Checkbox(String label, It constructs a checkbox with the


CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

boolean state, given label, set the given state in


CheckboxGroup group) the specified checkbox group.

5. Checkbox(String label, It constructs a checkbox with the


CheckboxGroup group, given label, in the given checkbox
boolean state) group and set to the specified state.

Method inherited by Checkbox

The methods of Checkbox class are inherited by following classes:

o java.awt.Component
o java.lang.Object

Checkbox Class Methods

Sr. Method name Description


no.

1. void addItemListener(ItemListener It adds the given item


IL) listener to get the item
events from the checkbox.

2. AccessibleContext It fetches the accessible


getAccessibleContext() context of checkbox.

3. void addNotify() It creates the peer of


checkbox.

4. CheckboxGroup It determines the group of


getCheckboxGroup() checkbox.

5. ItemListener[] getItemListeners() It returns an array of the


item listeners registered
on checkbox.

6. String getLabel() It fetched the label of


checkbox.

7. T[] getListeners(Class listenerType) It returns an array of all


the objects registered as
FooListeners.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

8. Object[] getSelectedObjects() It returns an array (size 1)


containing checkbox 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 paramString() It returns a string


representing the state of
checkbox.

11. protected void It processes the event on


processEvent(AWTEvent e) checkbox.

12. protected void It process the item events


processItemEvent(ItemEvent e) occurring in the checkbox
by dispatching them to
registered ItemListener
object.

13. void It removes the specified


removeItemListener(ItemListener l) item listener so that the
item listener doesn't
receive item events from
the checkbox anymore.

14. void It sets the checkbox's


setCheckboxGroup(CheckboxGroup group to the given
g) checkbox.

15. void setLabel(String label) It sets the checkbox's label


to the string argument.

16. void setState(boolean state) It sets the state of


checkbox to the specified
state.

Java Code With CheckBox and its ItemListener:

package test1;
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

import java.awt.*;
import java.awt.event.*;
public class CheckboxExample2
{
CheckboxExample2() {
Frame f = new Frame ("CheckBox Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100, 150, 50, 50);
f.add(checkbox1);f.add(checkbox2);f.add(label);
checkbox1.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
label.setText("c++
CheckBox:"+(e.getStateChange()==1?"changed":"unchanged"));

}
});

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);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
f.dispose();
}
});
}
// main method
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

public static void main(String args[])


{
new CheckboxExample2();
}
}

Output:

CheckboxGroup:

The object of CheckboxGroup class is used to group together a set of Checkbox.


At a time only one check box button is allowed to be in "on" state and
remaining check box button in "off" state. It inherits the object class.

Note: CheckboxGroup enables you to create radio buttons in AWT. There is no


special control for creating radio buttons in AWT.

Code With CheckBoxGroup with ItemListner:

package test1;
import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
final Label label = new Label();
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

label.setAlignment(Label.CENTER);
label.setSize(400,100);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, false);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
checkBox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ checkbox: Checked");
}
});
checkBox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java checkbox: Checked");
}
});
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}

Output:
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Choice:

The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits Component class.

Choice Class constructor

Sr. no. Constructor Description

1. Choice() It constructs a new choice menu.

Methods inherited by class

The methods of Choice class are inherited by following classes:

o java.awt.Component
o java.lang.Object
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Choice Class Methods

Sr. Method name Description


no.

1. void add(String item) It adds an item to the choice


menu.

2. void It adds the item listener that


addItemListener(ItemListener l) receives item events from the
choice menu.

3. void addNotify() It creates the peer of choice.

4. AccessibleContext It gets the accessbile context


getAccessibleContext() related to the choice.

5. String getItem(int index) It gets the item (string) at the


given index position in the
choice menu.

6. int getItemCount() It returns the number of items


of the choice menu.

7. ItemListener[] getItemListeners() It returns an array of all item


listeners registered on choice.

8. T[] Returns an array of all the


getListeners(Class listenerType) objects currently registered as
FooListeners upon this
Choice.

9. int getSelectedIndex() Returns the index of the


currently selected item.

10. String getSelectedItem() Gets a representation of the


current choice as a string.

11. Object[] getSelectedObjects() Returns an array (length 1)


containing the currently
selected item.

12. void insert(String item, int index) Inserts the item into this
choice at the specified
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

position.

13. protected String paramString() Returns a string representing


the state of this Choice menu.

14. protected void It processes the event on the


processEvent(AWTEvent e) choice.

15. protected void processItemEvent Processes item events


(ItemEvent e) occurring on this Choice
menu by dispatching them to
any registered ItemListener
objects.

16. void remove(int position) It removes an item from the


choice menu at the given
index position.

17. void remove(String item) It removes the first


occurrence of the item from
choice menu.

18. void removeAll() It removes all the items from


the choice menu.

19. void removeItemListener It removes the mentioned


(ItemListener l) item listener. Thus is doesn't
receive item events from the
choice menu anymore.

20. void select(int pos) It changes / sets the selected


item in the choice menu to
the item at given index
position.

21. void select(String str) It changes / sets the selected


item in the choice menu to
the item whose string value is
equal to string specified in
the argument.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Java Code on Choice with ActionListner:

package test1;
import java.awt.*;
import java.awt.event.*;

public class ChoiceExample2 {


ChoiceExample2() {
Frame f = new Frame();
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400, 100);
Button b = new Button("Show");
b.setBounds(200, 100, 50, 20);
final Choice c = new Choice();
c.setBounds(100, 100, 75, 75);
c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
f.add(c);
f.add(label);
f.add(b);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+
c.getItem(c.getSelectedIndex());
label.setText(data);
}
});
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
f.dispose();
}
});
}

// main method
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

public static void main(String args[])


{
new ChoiceExample2();
}
}

Output:

Canvas:

he Canvas class controls and represents a blank rectangular area where the
application can draw or trap by the user.

Canvas Class Constructors

Sr. Constructor Description


no.

1. Canvas() It constructs a new Canvas.

2. Canvas(GraphicConfiguration It constructs a new Canvas


config) with the given Graphic
Configuration object.

Class methods
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Sr. Method name Description


no.

1. void addNotify() It creates the canvas's peer.

2. void createBufferStrategy (int It creates a new multi buffering


numBuffers) strategies on the particular
component.

3. void createBufferStrategy (int It creates a new multi buffering


numBuffers, BufferCapabilities strategies on the particular
caps) component with the given
buffer capabilities.

4. AccessibleContext It gets the accessible context


getAccessibleContext() related to the Canvas.

5. BufferStrategy It returns the buffer strategy


getBufferStrategy() used by the particular
component.

6. void paint(Graphics g) It paints the canvas with given


Graphics object.

7. void pdate(Graphics g) It updates the canvas with


given Graphics object.

Method Inherited by Canvas Class

The Canvas has inherited above methods from the following classes:

o lang.Component
o lang.Object

Java code for Canvas:

package test1;
import java.awt.*;
public class CanvasExample
{

public CanvasExample()
{
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

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


f.add(new MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
public static void main(String args[])
{
new CanvasExample();
}
}
class MyCanvas extends Canvas
{
// class constructor
public MyCanvas() {
setBackground (Color.blue);
setSize(300, 200);
}

// paint() method to draw inside the canvas


public void paint(Graphics g)
{

// adding specifications
g.setColor(Color.orange);
g.fillOval(75, 75, 150, 75);
}
}

Output:
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Panel:

The Panel is a simplest container class. It provides space in which an


application can attach any other component. It inherits the Container class.

Dialog:
The Dialog control represents a top level window with a border and a title used
to take some form of input from the user. It inherits the Window class.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Unlike Frame, it doesn't have maximize and minimize buttons.

Frame vs Dialog

Frame and Dialog both inherits Window class. Frame has maximize and
minimize buttons but Dialog doesn't have.

Example On Dialog

MenuBar, MenuItem and Menu:

The object of MenuItem class adds a simple labeled menu item on menu. The
items used in a menu must belong to the MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on
the menu bar. It inherits the MenuItem class.

Code on MenuItem and Menu:

package test1;
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Menu menu=new Menu("Menu");


Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}

Output:
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Scrollbar:

The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and
columns.

Scrollbar Class Fields

The fields of java.awt.Image class are as follows:

ADVERTISEMENT
ADVERTISEMENT

o static int HORIZONTAL - It is a constant to indicate a horizontal scroll


bar.
o static int VERTICAL - It is a constant to indicate a vertical scroll bar.

Scrollbar Class Constructors

Sr. Constructor Description


no.

1 Scrollbar() Constructs a new vertical scroll bar.


CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

2 Scrollbar(int orientation) Constructs a new scroll bar with the


specified orientation.

3 Scrollbar(int orientation, Constructs a new scroll bar with the


int value, int visible, int specified orientation, initial value,
minimum, int maximum) visible amount, and minimum and
maximum values.

Where the parameters,

o orientation: specifiey whether the scrollbar will be horizontal or vertical.


o Value: specify the starting position of the knob of Scrollbar on its track.
o Minimum: specify the minimum width of track on which scrollbar is
moving.
o Maximum: specify the maximum width of track on which scrollbar is
moving.

Scrollbar Class Methods

Sr. Method name Description


no.

1. void addAdjustmentListener It adds the given adjustment


(AdjustmentListener l) listener to receive instances
of AdjustmentEvent from
the scroll bar.

2. void addNotify() It creates the peer of scroll


bar.

3. int getBlockIncrement() It gets the block increment


of the scroll bar.

4. int getMaximum() It gets the maximum value


CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

of the scroll bar.

5. int getMinimum() It gets the minimum value of


the scroll bar.

6. int getOrientation() It returns the orientation of


scroll bar.

7. int getUnitIncrement() It fetches the unit increment


of the scroll bar.

8. int getValue() It fetches the current value


of scroll bar.

9. int getVisibleAmount() It fetches the visible amount


of scroll bar.

10. boolean getValueIsAdjusting() It returns true if the value is


in process of changing where
action results are being taken
by the user.

11. protected String paramString() It returns a string


representing the state of
Scroll bar.

12. protected void It processes the adjustment


processAdjustmentEvent event occurring on scroll bar
(AdjustmentEvent e) by dispatching them to any
registered
AdjustmentListener objects.

13. protected void It processes the events on the


processEvent(AWTEvent e) scroll bar.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

14. void removeAdjustmentListener It removes the given


(AdjustmentListener l) adjustment listener. Thus it
no longer receives the
instances of
AdjustmentEvent from the
scroll bar.

15. void setBlockIncrement(int v) It sets the block increment


from scroll bar.

16. void setMaximum (int It sets the maximum value of


newMaximum) the scroll bar.

17. void setMinimum (int It sets the minimum value of


newMinimum) the scroll bar.

18. void setOrientation (int It sets the orientation for the


orientation) scroll bar.

19. void setUnitIncrement(int v) It sets the unit increment for


the scroll bar.

20. void setValue (int newValue) It sets the value of scroll bar
with the given argument
value.

21. void setValueIsAdjusting (boolean It sets the valueIsAdjusting


b) property to scroll bar.

22. void setValues (int value, int It sets the values of four
visible, int minimum, int properties for scroll bar:
maximum) value, visible amount,
minimum and maximum.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

23. void setVisibleAmount (int It sets the visible amount of


newAmount) the scroll bar.

24. AccessibleContext It gets the accessible context


getAccessibleContext() related to the scroll bar.

25. AdjustmentListener[] It returns an array of al lthe


getAdjustmentListeners() adjustment listeners
registered on the scroll bar.

26. T[] It returns an array if all


getListeners(Class listenerType) objects that are registered as
FooListeners on the scroll
bar currently.

Scrollbar Example with AdjustmentListener:

package test1;
import java.awt.*;
import java.awt.event.*;
public class ScrollbarExample2 {
// class constructor
ScrollbarExample2() {
// creating a Frame with a title
Frame f = new Frame("Scrollbar Example");
// creating a final object of Label
final Label label = new Label();
// setting alignment and size of label object
label.setAlignment(Label.CENTER);
label.setSize(400, 100);
// creating a final object of Scrollbar class
final Scrollbar s = new Scrollbar();
// setting the position of scroll bar
s.setBounds(100, 100, 50, 100);
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

// adding Scrollbar and Label to the Frame


f.add(s);
f.add(label);
// setting the size, layout, and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
// adding AdjustmentListener to the scrollbar object
s.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical Scrollbar value is:"+ s.getValue());
}
});
}

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

Output:
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Java LayoutManagers

The LayoutManagers are used to arrange components in a particular manner.


The Java LayoutManagers facilitates us to control the positioning and size of
the components in GUI forms. LayoutManager is an interface that is
implemented by all the classes of layout managers. There are the following
classes that represent the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north,


south, east, west, and center. Each region (area) may contain one component
only. It is the default layout of a frame or window. The BorderLayout provides
five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the
components.
o BorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Example of BorderLayout class: Using BorderLayout() constructor

Java GridLayout

The Java GridLayout class is used to arrange the components in a rectangular


grid. One component is displayed in each rectangle.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a
row.
2. GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns along with given horizontal and
vertical gaps.

Example of GridLayout class: Using GridLayout() Constructor

The GridLayout() constructor creates only one row. The following example
shows the usage of the parameterless constructor.
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Example of GridLayout class: Using GridLayout(int rows, int columns)


Constructor
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Java FlowLayout

The Java FlowLayout class is used to arrange the components in a line, one
after another (in a flow). It is the default layout of the applet or panel.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a
default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment
and a default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with
the given alignment and the given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor


CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Java CardLayout

The Java CardLayout class manages the components in such a manner that
only one component is visible at a time. It treats each component as a card that
is why it is known as CardLayout.

Constructors of CardLayout Class


1. CardLayout(): creates a card layout with zero horizontal and vertical
gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.

Commonly Used Methods of CardLayout Class


o public void next(Container parent): is used to flip to the next card of
the given container.
o public void previous(Container parent): is used to flip to the previous
card of the given container.
o public void first(Container parent): is used to flip to the first card of
the given container.
o public void last(Container parent): is used to flip to the last card of the
given container.
o public void show(Container parent, String name): is used to flip to the
specified card with the given name.

Example of CardLayout Class: Using Default Constructor

The following program uses the next() method to move to the next card of the
container.

package test1;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class CardLayoutExample1 extends JFrame implements ActionListener


{
CardLayout crd;
JButton btn1, btn2, btn3;
Container cPane;
CardLayoutExample1()
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

{
cPane = getContentPane();
crd = new CardLayout();
cPane.setLayout(crd);
btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
cPane.add("a", btn1);
cPane.add("b", btn2);
cPane.add("c", btn3);
}
public void actionPerformed(ActionEvent e)
{
crd.next(cPane);
}
public static void main(String argvs[])
{
CardLayoutExample1 crdl = new CardLayoutExample1();
crdl.setSize(300, 300);
crdl.setVisible(true);
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

Output:
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

Java GridBagLayout

The Java GridBagLayout class is used to align components vertically,


horizontally or along their baseline.

The components may not be of the same size. Each GridBagLayout object
maintains a dynamic, rectangular grid of cells. Each component occupies one or
more cells known as its display area. Each component associates an instance of
GridBagConstraints. With the help of the constraints object, we arrange the
component's display area on the grid. The GridBagLayout manages each
component's minimum and preferred sizes in order to determine the
component's size. GridBagLayout components are also arranged in the
rectangular grid but can have many different sizes and can occupy multiple
rows or columns.

Code:

package test1;
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame
{
public static void main(String[] args)
{
GridBagLayoutExample a = new GridBagLayoutExample();
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

}
public GridBagLayoutExample()
{
GridBagLayout GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(GridBagLayoutgrid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 40;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

Output:
CMRCET CSE JAVA UNIT IV PART -1 NOTES JAVA AWT

You might also like