[go: up one dir, main page]

0% found this document useful (0 votes)
52 views49 pages

Adj 01

Uploaded by

thakkarparth793
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)
52 views49 pages

Adj 01

Uploaded by

thakkarparth793
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/ 49

ADJ CHAPTER 01

Introduction to AWT :

● AWT stands for Abstract Window Toolkit


● Java AWT or Abstract Window Toolkit is an API used for developing
GUI(Graphic User Interfaces) or Window-Based Applications in Java.
● Java AWT is part of the Java Foundation Classes (JFC) that provides
a way to build platform-independent graphical applications.
● Java AWT components are platform-dependent, which means they
are shown in accordance with the operating system’s view.
● AWT is heavyweight, which means that its components consume
resources from the underlying operating system (OS).
● The java.awt package contains AWT API classes such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List, and so on.
AWT consist of 12packages but only 2 are most commonly used: java.awt
and java.awt.event package.
Why AWT is Platform Independent?
mistake Why AWT is platform Dependent?

● The Java AWT utilizes the native platform subroutine to create API
components such as TextField, CheckBox, and buttons.
● This results in a different visual format for these components on
different platforms such as Windows, MAC OS, and Unix.
● The reason for this is that each platform has a distinct view of its
native components.
● AWT directly calls this native subroutine to create the components,
resulting in an AWT application resembling a Windows application
on Windows OS, and a Mac application on the MAC OS. In simpler
terms, the AWT application’s appearance adapts to the platform it is
running on.
● AWT is platform independent even after the AWT components are
platform dependent because of the points mentioned below:
1. JVM (Java Virtual Machine):As Java Virtual Machine is platform
dependent
2. Abstract APIs:AWT provides an abstract layer for GUI. Java
applications interact with AWT through Abstract API which are
platform independent. Abstract API allows Java to isolate
platform-specific details, making code portable across different
systems.
3. Platform-Independent Libraries: The Libraries of AWT are written
in Java which they are totally platform-independent. Because of this,
it ensures that AWT functionality remains consistent across different
environments.
Java AWT Hierarchy :

● Components: AWT provides various components such as buttons, labels,

text fields, checkboxes, etc used for creating GUI elements for Java

Applications.

● Containers: AWT provides containers like panels, frames, and dialogues to

organize and group components in the Application.

● Layout Managers: Layout Managers are responsible for arranging data in the

containers some of the layout managers are BorderLayout, FlowLayout, etc.


● Event Handling: AWT allows the user to handle the events like mouse clicks,

key presses, etc. using event listeners and adapters.

● Graphics and Drawing: It is the feature of AWT that helps to draw shapes,

insert images and write text in the components of a Java Application.

Components are added to containers, and layout managers dictate their placement within the
container. This hierarchy allows you to build complex user interfaces by organizing smaller
components into well-structured containers.

Container

● The Container is a component in AWT that can contain another


components like buttons, textfields, labels etc.
● The classes that extends Container class are known as container
such as Frame, Dialog and Panel.
● It is basically a screen where the where the components are placed
at their specific locations. Thus it contains and controls the layout of
components.

Note: A container itself is a component (see the above diagram), therefore


we can add a container inside container
Types of Containers in Java AWT
There are four types of containers in Java AWT:

1. Window: Window is a top-level container that represents a

graphical window or dialog box. The Window class extends the

Container class, which means it can contain other components, such

as buttons, labels, and text fields. The window is the container that

have no borders and menu bars.

2. Panel: Panel is a container class in Java. It is a lightweight container

that can be used for grouping other components together within a

window or a frame.The Panel is the container that doesn't contain

title bar, border or menu bar.

3. Frame: The Frame is the container that contains the 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.

4. Dialog: A dialog box is a temporary window an application creates

to retrieve user input.

Components
● All the elements like the button, text fields, scroll bars, etc. are
called components.
● In Java AWT, there are classes for each component as shown in
above diagram.
● In order to place every component in a particular position on a
screen, we need to add them to a container.

Frame in Java

● Frame in java is a container which is able to manage other gui components


like button , text fields, scrollbar , etc
● The frame is a container that contain title bar and border and can have menu
bar.
● To represent frame in GUI applications , Java has provided a separate predefined
class java.awt.Frame.
● Frame is the most widely used container while developing GUI applications.
● The default layout for a frame is BorderLayout.

Hierarchy :
Component → Container → Window → Frame

Syntax :
public class Frame
extends Window
implements MenuContainer
{
}

2 ways of creating Frame :


1) By creating the object of the Frame class
2) By creating object of Frame class

By creating the object of the Frame class

import java.awt.*;
class Sample{
Sample(){
Frame f = new Frame();
f.setVisible(true);
f.setLayout(null);
f.setSize(500,500);
f.setTitle("hello I am a frame created by object");
}
public static void main(String args[]){
Sample s = new Sample();

}}

3) By extending the Frame class:

import java.awt.*;
class Sample extends Frame{
Sample(){
this.setVisible(true);
this.setLayout(null);
this.setSize(500,500);
this.setTitle("hello");
}
public static void main(String args[]){
Sample s = new Sample();
}
}
Panel

https://www.geeksforgeeks.org/java-awt-panel/

AWT Panel class declaration


1. public class Panel extends Container implements Accessible

● Panel inherits the Container class.


Label
1. Java AWT Label

What is Label in Java AWT?


● Label in Java AWT is a component for placing text or images in a container. It is
used to display a single line of read only text.
● The text displayed in the Container (Display) by Java AWT Label can’t be edited
directly by the user but needs the programmer to change it from his side.
● To create a label, we need to create the object of Label class.
● Note: Java AWT Label is also called passive control as no event is created
when it is accessed.

Syntax of AWT Label


public class Label extends Component implements Accessible

AWT Label Class Constructors

There are three types of Java AWT Label Class

1. Label():
Creates Empty Label.

2. Label(String str):
Constructs a Label with str as its name.

3. Label(String str, int alignment ):


Constructs a label with the specified string and alignment as the specified
alignment ( Label.LEFT , Label.RIGHT , Label.CENTER

Java AWT Label Fields


Java AWT Labels have 3 fields there can also be determined as the
java.awt.Component class fields. All of them are mentioned below:
Java AWT Label Fields Description

static int LEFT It specifies that the label is aligned left.

static int RIGHT It specifies that the label is aligned right.

static int CENTER It specifies that the label is aligned center.

Java AWT Label Class Methods


There are a few predefined Methods associated with Java AWT Label as
mentioned below:

Sr.
No. Method Description

1. void setText(String text) Sets the text of the label.


2. String getText() Gets the text of the label.

Sets the alignment of the text in the label.

3. void setAlignment(int
alignment) Possible values: Label.LEFT, Label.RIGHT,
Label.CENTER.

4. int getAlignment() Gets the alignment of the text in the label.

5. void addNotify() Creates the peer for the label.

6. AccessibleContext Gets the AccessibleContext associated with


getAccessibleContext() the label.

7. void addNotify() Creates the peer (native window) for the label.

Methods inherited
The Methods provided with AWT Label is inherited by classes mentioned
below:

● java.awt.Component

● java.lang.Object

Program:

import java.awt.*;
class Sample extends Frame{
Sample(){
this.setVisible(true);
this.setSize(500,500);
this.setLayout(null);
this.setTitle("Label");

Label l = new Label("HELLO");


l.setBounds(200,200,100,50);
l.setAlignment(Label.CENTER);
this.add(l);

}
public static void main(String args[]){
Sample s = new Sample();
}

Button in java
Syntax of Java AWT Button

public class Button extends Component implements Accessible

Inherited Methods

The Methods included with AWT button are inherited by:

● java.awt.Component

● java.lang.Object
● Note: The Button class inherits methods from java.awt.Component and
java.lang.Object classes.

https://www.geeksforgeeks.org/java-awt-button/

https://www.javatpoint.com/java-awt-button

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

Syntax :
public class Checkbox extends Component implements ItemSelectable, Accessible

Methods of checkbox class are inherited by two classes:

● java.awt.Component

● java.lang.Object

https://www.geeksforgeeks.org/java-awt-checkbox/?ref=ml_lbp
CheckBox Group

Java AWT 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.

The CheckboxGroup class is declared as follows:

public class CheckboxGroup extends Object implements Serializable


Program :

import java.awt.*;

import java.awt.event.*;

class Sample{

Sample(){

Frame f = new Frame();

f.setVisible(true);

f.setSize(500,500);

f.setTitle("I am a Frame");

f.setLayout(null);

CheckboxGroup cbg = new CheckboxGroup();

Checkbox c1 = new Checkbox("Java",cbg,true);

Checkbox c2 = new Checkbox("CPP",cbg,false);

Checkbox c3 = new Checkbox("Python",cbg,false);

c1.setBounds(50,50,100,20);

c2.setBounds(50,90,100,20);

c3.setBounds(50,130,100,20);

f.add(c1);

f.add(c2);

f.add(c3);
Label l = new Label();

l.setBounds(50,250,100,50);

f.add(l);

Button b1 = new Button("Get the selected one : ");

b1.setBounds(50,170,200,50);

f.add(b1);

b1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

Checkbox cg = cbg.getSelectedCheckbox();

l.setText(cg.getLabel());

}});

public static void main(String args[]){

Sample s = new Sample();

}}
Java AWT Scrollbar
The ‘Scrollbar’ class is a part of the ‘java.awt’ package. Java AWT Scrollbars
are used for scrolling through content like text, images, or any other data that
doesn’t fit completely within the specified display area. The Scrollbar
component supports both vertical and horizontal scrolling. It generates
events when it is controlled by the user. We can add custom behavior using
different methods to improve the functionality of our application.
Syntax of Java AWT Scrollbar

public class Scrollbar extends Component implements Adjustable, Accessible

Fields of Java AWT Scrollbar


● static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.

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

Constructors of Java AWT Scrollbar


The table represents the Constructors present in the AWT Scrollbar with a
description.

Scrollbar Class Constructors

Sr. Constructor Description


no

1 Scrollbar() Constructs a new vertical scroll bar.

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

orientation.

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

value, int visible, int minimum, orientation, initial value, visible amount, and

int maximum) minimum and maximum values.

The parameters of the given constructors are:

● Orientation: The orientation of the scrollbar specifies whether it will

be horizontal or vertical.

● Value: The starting position of the Scrollbar’s knob on its track.

● Minimum: The smallest width of the track on which the scrollbar

moves.

● Maximum: The maximum width of the track on which the scrollbar

moves.
Inherited Fields

The Fields of AWT Scrollbar are inherited by:

● java.awt.Component

● java.awt.Adjustable

● java.awt.image.ImageObserver

Scrollbar Class Methods


Sr. Method name Description
no
.

1. void addAdjustmentListener It adds the given adjustment listener to

(AdjustmentListener l) 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 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 event

processAdjustmentEvent occurring on scroll bar by dispatching them

(AdjustmentEvent e) to any registered AdjustmentListener

objects.

13. protected void It processes the events on the scroll bar.

processEvent(AWTEvent e)

14. void removeAdjustmentListener It removes the given adjustment listener.

(AdjustmentListener l) 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 the scroll bar.

newMaximum)

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

newMinimum)

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

orientation)

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 It sets the valueIsAdjusting property to

(boolean b) scroll bar.

22. void setValues (int value, int It sets the values of four properties for

visible, int minimum, int scroll bar: value, visible amount, minimum

maximum) and maximum.

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

newAmount)
24. AccessibleContext It gets the accessible context related to the

getAccessibleContext() scroll bar.

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

getAdjustmentListeners() listeners registered on the scroll bar.

26. T[] getListeners(Class It returns an array if all objects that are

listenerType) registered as FooListeners on the scroll bar

currently.

Inherited Methods

The Methods included with AWT Scrollbar are inherited by:

● java.awt.Component

● java.lang.Object

Program:

import java.awt.*;
class Sample{
Sample(){
Frame f = new Frame("This is a frame");
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);

Scrollbar s = new Scrollbar();


s.setBounds(50,50,50,200);
f.add(s);
Scrollbar s2 = new Scrollbar(Scrollbar.HORIZONTAL);
s2.setBounds(50,300,200,50);
f.add(s2);

Label l = new Label("Horizontal scrollbar");


l.setBounds(300,300,150,50);
f.add(l);
Label l2 = new Label("Vertical scrollbar");
l2.setBounds(300,50,150,50);
f.add(l2);

}
public static void main(String args[]){
Sample s = new Sample();
}}

TextField in Java AWT


The TextField class in Java AWT is a GUI component in the ‘java.awt’
package. It allows the user to enter a single line of text as an input. It is a
simple way to collect text-based information from the user. You can use the
TextField component to create various input fields for username, password,
search boxes, etc.

Whenever a key is pressed or typed into the input field, an event is sent to
the TextField. The registered KeyListener then receives the KeyEvent.
ActionEvent can also be used for this purpose. If the ActionEvent is
configured on the text field, then it will be triggered when the Return key is
pressed. The ActionListener interface handles the event.

Syntax of Java AWT TextField

public class TextField extends TextComponent

Class Constructors of AWT TextField

1. TextField(): Constructs a new text field component

2. TextField(int columns): Constructs a new empty text field with the

required number of columns as the parameter.

3. TextField(String text): Creates a new text field initialized with the

string text to be displayed.

4. TextField(String text, int columns): Creates a new text field with

the given text to be displayed and a width that fits the specified

number of columns.

TextField Class Methods


Method name Description

void addNotify() It creates the peer of text field.

boolean echoCharIsSet() It tells whether text field has

character set for echoing or not.

void It adds the specified action listener

addActionListener(ActionLi to receive action events from the

stener l) text field.

ActionListener[] It returns array of all action

getActionListeners() listeners registered on text field.

AccessibleContext It fetches the accessible context

getAccessibleContext() related to the text field.


int getColumns() It fetches the number of columns in

text field.

char getEchoChar() It fetches the character that is used

for echoing.

Dimension It fetches the minimum dimensions

getMinimumSize() for the text field.

Dimension It fetches the minimum dimensions

getMinimumSize(int for the text field with specified

columns) number of columns.

Dimension It fetches the preferred size of the

getPreferredSize() text field.

Dimension It fetches the preferred size of the

getPreferredSize(int text field with specified number of

columns) columns.
protected String It returns a string representing state

paramString() of the text field.

protected void It processes action events

processActionEvent(Action occurring in the text field by

Event e) dispatching them to a registered

ActionListener object.

protected void It processes the event on text field.

processEvent(AWTEvent e)

void It removes specified action listener

removeActionListener(Acti so that it doesn't receive action

onListener l) events anymore.

void setColumns(int It sets the number of columns in

columns) text field.


void setEchoChar(char c) It sets the echo character for text

field.

void setText(String t) It sets the text presented by this

text component to the specified

text.
Inherited Methods
The Methods included with AWT TextField are inherited by:

● java.awt.TextComponent

● java.lang.Component

● java.lang.Object

Programs:
import java.awt.*;
import java.awt.event.*;
class Sample{
Sample(){
Frame f = new Frame();
f.setVisible(true);
f.setTitle("I am a Frame");
f.setLayout(null);
f.setSize(500,500);

TextField t1 = new TextField();


t1.setText("hello");
t1.setBounds(50,50,100,50);
t1.setEditable(false);
System.out.println("Is editable ? : "+ t1.isEditable());

TextField t2 = new TextField();


t2.setBounds(50,120,100,50);
t2.setEchoChar('*');
TextField t3 = new TextField();
t3.setBounds(50,190,100,50);

Label l = new Label();


l.setBounds(50,300,100,50);
f.add(l);

Button b = new Button("Click");


b.setBounds(50,260,100,50);
f.add(b);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
l.setText(t3.getText());
}
});

f.add(t1);
f.add(t2);
f.add(t3);
}
public static void main(String args[]){
Sample s = new Sample();
}}
TextArea

The TextArea control in AWT provide us multiline editor area. The user can type here
as much as he wants. When the text in the text area become larger than the viewable
area the scroll bar is automatically appears which help us to scroll the text up & down
and right & left. It allows the editing of multiple line text. It inherits TextComponent
class.
AWT TextArea Class Declaration
public class TextArea extends TextComponent

TextArea class Fields

● 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

TextArea Constructors
1 TextArea()
Constructs a new text area with the empty string as text.

2 TextArea(int rows, int columns)


Constructs a new text area with the specified number of rows and columns and
the empty string as text.

3 TextArea(String text)
Constructs a new text area with the specified text.
4 TextArea(String text, int rows, int columns)
Constructs a new text area with the specified text, and with the specified number
of rows and columns.

5 TextArea(String text, int rows, int columns, int scrollbars)


Constructs a new text area with the specified text, and with the rows, columns,
and scroll bar visibility as specified.

Methods Inherited :

● java.awt.TextComponent

● java.awt.Component

● java.lang.Object

Program :
import java.awt.*;
import java.awt.event.*;

class Sample{
Sample(){
Frame f = new Frame("This is a Frame");
f.setVisible(true);
f.setSize(500,500);
f.setLayout(null);

TextArea t = new TextArea();


t.setBounds(100,50,100,100);
f.add(t);
}
public static void main(String args[]){
Sample s = new Sample();
}}

Layout Manager

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) FlowLayout
● FlowLayout is used to arrange components in a sequence one after the
other.
● The default layout of applet and panel is FlowLayout.

Commonly used methods:


● setTitle(String Text): This Method is used to set Title of JFrame. The

title you want to set is passed as a string.

● removeLayoutComponent(Component comp): Used to remove the

component passed as argument from the layout.


Fields of FlowLayout class

● public static final int LEFT

● public static final int RIGHT

● public static final int CENTER

● public static final int LEADING

● public static final int TRAILING

Programs:
import java.awt.*;
import java.awt.event.*;
class Sample{
Sample(){

Frame f = new Frame();


f.setVisible(true);
f.setSize(500,500);
f.setLayout(new FlowLayout(FlowLayout.LEFT,50,50));
// int alignment , int hgap , int vgap
f.setTitle("This is flowlayout");

Button b1 = new Button("b1");


Button b2 = new Button("b2");
Button b3 = new Button("b3");
Button b4 = new Button("b4");
Button b5 = new Button("b5");

f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
}
public static void main(String args[]){
Sample s = new Sample();
}}

Border Layout
BorderLayout is the default layout for the window objects such as JFrame,
JWindow, JDialog, JInternalFrame etc. BorderLayout arranges the
components in the five regions. Four sides are referred to as north, south,
east, and west. The middle part is called the center. Each region can contain
only one component and is identified by a corresponding constant as NORTH,
SOUTH, EAST, WEST, and CENTER.

BorderLayout Fields

● public static final int NORTH

● public static final int SOUTH

● public static final int EAST

● public static final int WEST

● public static final int CENTER

Commonly Used Methods:


● toString(): Returns a string which is the representation of the state of

border layout.

● getLayoutAlignmentX(Container parent): Returns the layout alignment

along the X-axis.

● getLayoutAlignmentY(Container parent): It will return the layout

alignment along the Y-axis.

● removeLayoutComponent(Component comp): This method is used to

remove the specified component from the borderlayout.

● getVgap(): Return the vertical gap between the components.

● getHgap(): Returns the Horizontal gap between the components.


● setHgap(int hgap): It is used to set the horizontal gap between the

components.

● setVgap(int vgap): It is used to set the vertical gap between the

components.

GridLayout
● GridLayout class represents a layout manager with a specified number of
rows and columns in a rectangular grid.
● The GridLayout container is divided into an equal-sized of rectangles, and
one of the components is placed in each rectangle.
● Every rectangle cell has the same size therefore, they contain a
component, which fills the entire cell.
● When the user changes or adjusts the size of the container, the size of
each rectangles changes accordingly.
Constructors of the class:
1. GridLayout(): It Creates a grid layout with a default of one column per

component, in a single row.

2. GridLayout(int rw, int cl): It creates a grid layout with the specified

number of rows and columns.

3. GridLayout(int rw, int cl, int hgap, int vgap): It creates a grid layout

with the specified number of rows and columns with horizontal and

vertical gap.

Commonly Used Methods:


● addLayoutComponent(String str, Component cmp): Adds the

specified component with the specified name to the layout.


● setColumns(int cl): Sets the number of columns in this layout to the

specified value.

● setHgap(int hgap): Sets the horizontal gap between components to

the specified value.

● setRows(int rw): Sets the number of rows in this layout to the

specified value.

● setVgap(int vgap): Sets the vertical gap between components to the

specified value.

● layoutContainer(Container pr): Lays out the specified container using

this layout.

● toString(): Returns the string representation of this grid layout’s

values.
Card Layout

You might also like