UNIT 1 AWT
UNIT 1 AWT
UNIT 1 AWT
1.1 Component:
java.lang.Object
java.awt.Component
A component is an object having a graphical representation that can be displayed on the screen and that can
interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical
graphical user interface.
The Component class is the abstract superclass of the nonmenu-related Abstract Window Toolkit components.
Class Component can also be extended directly to create a lightweight component. A lightweight component is
a component that is not associated with a native window. On the contrary, a heavyweight component is
associated with a native window. The isLightweight() method may be used to distinguish between the two kinds
of the components.
1.2 Container
java.lang.Object
java.awt.Component
java.awt.Container
generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT
components.
Components added to a container are tracked in a list. The order of the list will define the components' front-to-
back stacking order within the container. If no index is specified when adding a component to a container, it
will be added to the end of the list (and hence to the bottom of the stacking order).
1.3 Window
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
A Window object is a top-level window with no borders and no menubar. The default layout for a window
is BorderLayout.
A window must have either a frame, dialog, or another window defined as its owner when it's constructed.
1.4 Panel
java.lang.Object
Prof. A S Salavi (Kumbhar) Page 1 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
java.awt.Component
java.awt.Container
java.awt.Panel
Panel is the simplest container class. A panel provides space in which an application can attach any other
component, including other panels.
The default layout manager for a panel is the FlowLayout layout manager.
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs
inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
Hierarchy of Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
Prof. A S Salavi (Kumbhar) Page 2 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
4. Applet is stopped.
5. Applet is destroyed.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods
for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be
used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create an html file and place the
applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it.
After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}
}
/*
c:\>javac First.java
c:\>appletviewer First.java
1.2 Frame
Frame: A frame has title, border and menu bars. It can contain several components like buttons, text
fields, scrollbars etc. This is most widely used container while developing an application in AWT.
import java.awt.*;
/* We have extended the Frame class here,
* thus our class "SimpleExample" would behave
* like a Frame
*/
public class SimpleExample extends Frame{
SimpleExample(){
Button b=new Button("Button!!");
3) AWT Controls
1 Label
A Label object is a component for placing text in a container.
2 Button
This class creates a labeled button.
3 Check Box
A check box is a graphical component that can be in either an on (true) or off (false)
state.
5 List
The List component presents the user with a scrolling list of text items.
6 Text Field
A TextField object is a text component that allows for the editing of a single line of text.
7 Text Area
A TextArea object is a text component that allows for the editing of a multiple lines of
text.
8 Choice
9 Canvas
A Canvas control represents a rectangular area where application can draw something or
can receive inputs created by user.
10 Image
An Image control is superclass for all image classes representing graphical images.
11 Scroll Bar
A Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.
12 Dialog
A Dialog control represents a top-level window with a title and a border used to take
some form of input from the user.
13 File Dialog
A FileDialog control represents a dialog window from which the user can select a file.
1. Labels : This is the simplest component of Java Abstract Window Toolkit. This component is generally
used to show the text or string in your application and label never perform any type of action. Syntax for
defining the label only and with justification :
2. Buttons : This is the component of Java Abstract Window Toolkit and is used to trigger actions and
other events required for your application. The syntax of defining the button is as follow s :
3. Check Boxes : This component of Java AWT allows you to create check boxes in your applications.
The syntax of the definition of Checkbox is as follows :
4. Radio Button : This is the special case of the Checkbox component of Java AWT package. This is used
as a group of checkboxes which group name is same. Only one Checkbox from a Checkbox Group can
be selected at a time. Syntax for creating radio buttons is as follows :
5. Text Area: This is the text container component of Java AWT package. The Text Area contains plain
text. TextArea can be declared as follows:
6. Text Field: This is also the text container component of Java AWT package. This component contains
single line and limited text information. This is declared as follows :
Example:
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface
that is implemented by all the classes of layout managers. There are following classes that represents the layout
managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
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 frame or window. The BorderLayout
provides five constants for each region:
Prof. A S Salavi (Kumbhar) Page 9 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
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
o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.
import java.awt.*;
import javax.swing.*;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new Border();
}
}
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default
layout of applet or panel.
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.
import java.awt.*;
import javax.swing.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyFlowLayout();
}
}
Prof. A S Salavi (Kumbhar) Page 12 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
4.3 Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each
rectangle.
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 alongwith given horizontal and vertical gaps.
import java.awt.*;
import javax.swing.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyGridLayout();
}
}
The 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.
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.
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.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
Prof. A S Salavi (Kumbhar) Page 15 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e)
{
card.next(c);
}
The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline.
The components may not be of 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 constraints object we arrange component's display area on the
grid. The GridBagLayout manages each component's minimum and preferred sizes in order to determine
component's size.
Fields
protected layoutInfo It is used to hold the layout information for the gridbag.
GridBagLayoutInfo
protected static int MAXGRIDSI No longer in use just for backward compatibility
ZE
protected static int MINSIZE It is smallest grid that can be laid out by the grid bag
layout.
protected static int PREFERRED It is preferred grid size that can be laid out by the grid
SIZE bag layout.
Useful Methods
string.
protected Dimension getMinSize(Container parent, It figures out the minimum size of the
GridBagLayoutInfo info) master based on the information from
getLayoutInfo.
Example
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();
}
public GridBagLayoutExample()
{
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
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 = 20;
gbc.gridx = 0;
gbc.gridy = 1;
Prof. A S Salavi (Kumbhar) Page 19 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
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:
5) Menus
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.
Output:
6) Dialog box
Java AWT 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.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog doesn't
have.
Output:
7) File Dialog
FileDialog control represents a dialog window from which the user can select a file.
Class declaration
Following is the declaration for java.awt.FileDialog class
Class constructors
S.N. Constructor & Description
1 FileDialog(Dialog parent)
Creates a file dialog window with the specified title for loading a file.
Creates a file dialog window with the specified title for loading or saving a file.
4 FileDialog(Frame parent)
Creates a file dialog window with the specified title for loading a file.
Creates a file dialog window with the specified title for loading or saving a file.
Class methods
1 void addNotify()
2 String getDirectory()
3 String getFile()
4 FilenameFilter getFilenameFilter()
5 int getMode()
Indicates whether this file dialog box is for loading from a file or for saving to a
file.
Sets the directory of this file dialog window to be the specified directory.
Sets the selected file for this file dialog window to be the specified file.
Sets the filename filter for this file dialog window to the specified filter.
Methods inherited
This class inherits methods from the following classes:
java.awt.Dialog
java.awt.Window
java.awt.Component
java.lang.Object
FileDialog Example
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint
> gui >
AwtControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public AwtControlDemo(){
prepareGUI();
awtControlDemo.showFileDialogDemo();
mainFrame.setSize(400,400);
mainFrame.addWindowListener(new WindowAdapter() {
System.exit(0);
});
headerLabel.setAlignment(Label.CENTER);
statusLabel.setAlignment(Label.CENTER);
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
showFileDialogButton.addActionListener(new ActionListener() {
@Override
fileDialog.setVisible(true);
+ fileDialog.getDirectory() + fileDialog.getFile());
});
controlPanel.add(showFileDialogButton);
mainFrame.setVisible(true);
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo