Java Unit-5-Awt
Java Unit-5-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 [Link] 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.
Java AWT calls the native platform calls the native platform (operating systems) subroutine for
creating API components like TextField, ChechBox, button, etc.
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.
1
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.
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.
1. Window
2. Panel
3. Frame
4. 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.
Method Description
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager m) Defines the layout manager for the component.
public void setVisible(boolean status) Changes the visibility of the component, by default false.
2
Java AWT Example: To create simple AWT example, you need a frame. There are two ways to create
a GUI using Frame in AWT.
import [Link].*;
AWTExample1() {
[Link](30,100,80,30);
add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
} }
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example that
sets the position of the awt button.
Output:
3
AWT Example by Association: [Link]
import [Link].*;
class AWTExample2 {
AWTExample2() {
[Link](b);
[Link](l);
[Link](t);
[Link](400,300);
[Link]("Employee info");
[Link](null);
[Link](true);
} }
Output:
4
Java Swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.
The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
5) AWT doesn't follows MVC(Model View Controller) where Swing follows MVC.
model represents data, view represents presentation and
controller acts as an interface between model and view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of
desktop applications.
5
Commonly used Methods of Component class:
The methods of Component class are widely used in java swing that are given below.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
6
Java Swing Examples: There are two ways to create a frame:
import [Link].*;
7
JContainer components
Java JFrame: The [Link] class is a type of container which inherits the [Link]
class. JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI. Unlike Frame, JFrame has the option to hide or close the window with the
help of setDefaultCloseOperation(int) method.
Nested Class
protected class [Link] This class implements accessibility support for the JFrame
class.
Fields
static int EXIT_ON_CLOSE The exit application default window close operation.
protected boolean rootPaneCheckingEnabled If true then calls to add and setLayout will be
forwarded to the contentPane.
Constructors
Constructor Description
8
screen device and a blank title.
JFrame(String title) It creates a new, initially invisible Frame with the specified title.
JFrame(String title, It creates a JFrame with the specified title and the specified
GraphicsConfiguration gc) GraphicsConfiguration of a screen device.
Useful Methods
protected void addImpl(Component comp, Object Adds the specified child Component.
constraints, int index)
JFrame Example
import [Link];
import [Link];
import [Link];
import [Link];
9
import [Link];
[Link](new FlowLayout());
[Link]("Button");
[Link](label);
[Link](button);
[Link](panel);
[Link](200, 300);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
} }
Output
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JApplet class
extends the Applet class.
10
Example of EventHandling in JApplet:
import [Link].*;
import [Link].*;
import [Link].*;
JButton b;
JTextField tf;
tf=new JTextField();
[Link](30,40,150,20);
b=new JButton("Click");
[Link](80,150,70,40);
add(b);add(tf);
[Link](this);
setLayout(null);
[Link]("Welcome");
} }
In the above example, we have created all the controls in init() method because it is invoked only once.
[Link]
<html>
<body>
</applet>
</body>
</html>
11
Java JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.
Constructor Description
JPanel() It is used to create a new JPanel with a double buffer and a flow layout.
JPanel(boolean It is used to create a new JPanel with FlowLayout and the specified
isDoubleBuffered) buffering strategy.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager.
import [Link].*;
import [Link].*;
PanelExample()
[Link](40,80,200,200);
[Link]([Link]);
[Link](50,100,80,30);
12
[Link]([Link]);
[Link](100,100,80,30);
[Link]([Link]);
[Link](b1); [Link](b2);
[Link](panel);
[Link](400,400);
[Link](null);
[Link](true);
{ new PanelExample();
Output:
JSwing components
Java JButton: The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
13
JButton class declaration
Constructor Description
Methods Description
import [Link].*;
14
public static void main(String[] args) {
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true);
Output:
Java JLabel: The object of JLabel 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 an application but a user cannot
edit it directly. It inherits JComponent class.
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string
for the title.
15
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.
Methods Description
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.
import [Link].*;
class LabelExample
JLabel l1,l2;
[Link](50,50, 100,30);
16
[Link](50,100, 100,30);
[Link](l1); [Link](l2);
[Link](300,300);
[Link](null);
[Link](true);
Output:
Java JTextField: The object of a JTextField class is a text component that allows the editing of a
single line text. It inherits JTextComponent class.
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int columns) Creates a new TextField initialized with the specified text and columns.
17
JTextField(int columns) Creates a new empty TextField with the specified number of columns.
Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener to receive action
events from this textfield.
Action getAction() It returns the currently set Action for this ActionEvent source, or
null if no Action is set.
import [Link].*;
class TextFieldExample
JTextField t1,t2;
[Link](50,100, 200,30);
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
18
[Link](true);
Output:
Java JTextArea: The object of a JTextArea class is a multi line region that displays text. It allows
the editing of multiple line text. It inherits JTextComponent class
Constructor Description
JTextArea(int row, int Creates a text area with the specified number of
column) rows and columns that displays no text initially.
19
Methods Description
import [Link].*;
{ TextAreaExample(){
[Link](10,30, 200,200);
[Link](area);
[Link](300,300);
[Link](null);
[Link](true);
{ new TextAreaExample();
}}
20
Java LayoutManagers
There are the following classes that represent the layout managers:
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link] 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:
BorderLayout(): creates a border layout but with no gaps between the components.
BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.
import [Link].*;
import [Link].*;
{ JFrame f;
Border()
21
{ f = new JFrame();
[Link](300, 300);
[Link](true);
new Border();
} }
Output:
22
Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One component is
displayed in each rectangle.
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps
between the components.
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.
import [Link].*;
import [Link].*;
JFrame frameObj;
GridLayoutExample()
23
[Link](btn7); [Link](btn8); [Link](btn9);
[Link](new GridLayout());
[Link](300, 300);
[Link](true);
new GridLayoutExample();
} }
Output:
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.
FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and
vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal
and vertical gap.
24
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.
FileName: [Link]
import [Link].*;
import [Link].*;
{ JFrame frameObj;
FlowLayoutExample()
[Link](b9); [Link](b10);
[Link](new FlowLayout());
[Link](300, 300);
[Link](true);
25
public static void main(String argvs[])
{ new FlowLayoutExample();
Java BoxLayout
The Java BoxLayout class is used to arrange the components either vertically or horizontally. For this
purpose, the BoxLayout class provides four constants. They are as follows:
public static final int X_AXIS: Alignment of the components are horizontal from left to right.
public static final int Y_AXIS: Alignment of the components are vertical from top to bottom.
BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given
axis.
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.
CardLayout(): creates a card layout with zero horizontal and vertical gap.
CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.
public void next(Container parent): is used to flip to the next card of the given container.
public void previous(Container parent): is used to flip to the previous card of the given container.
public void first(Container parent): is used to flip to the first card of the given container.
public void last(Container parent): is used to flip to the last card of the given container.
public void show(Container parent, String name): is used to flip to the specified card with the given
name.
26
Event Handling
Event: Change in the state of an object is known as event i.e. event describes the change in state of
source.
Events are generated as result of user interaction with the graphical user interface components.
For example, clicking on a button, moving the mouse, entering a character through keyboard,
selecting an item from list, scrolling the page are the activities that causes an event to happen.
Types of Event: The events can be broadly classified into two categories:
1. Foreground Events - Those events which require the direct interaction of [Link] are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard,selecting an item from list, scrolling the page etc.
2. Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
Event Handling: Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs.
This mechanism have the code which is known as event handler that is executed when an
event occurs.
Steps involved in event handling:
The User clicks the button and the event is generated.
Now the object of concerned event class is created automatically and information
about the source and the event get populated with in same object.
Event object is forwarded to the method of registered listener class.
the method is now get executed and returns.
Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.
Delegation Event Model
The Delegation Event Model has the following key participants namely:
1. Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source
object.
2. Listener - It is also known as event [Link] is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener
waits until it receives an event. Once the event is received , the listener process the event an
then returns.
The benefit of this approach is that the user interface logic is completely separated from the
logic that generates the event.
The user interface element is able to delegate the processing of an event to the separate
piece of code.
In this model ,Listener needs to be registered with the source object so that the listener can
receive the event notification.
This is an efficient way of handling the event because the event notifications are sent only to
those listener that want to receive them.
27
The Delegation Model is available in Java since Java 1.1. it provides a new delegation-based
event model using AWT to resolve the event problems. It provides a convenient mechanism
to support complex Java programs.
Design Goals: The design goals of the event delegation model are as following:
It is easy to learn and implement
It supports a clean separation between application and GUI code.
It provides robust event handling program code which is less error-prone (strong compile-
time checking)
It is Flexible, can enable different types of application models for event flow and
propagation.
It enables run-time discovery of both the component-generated events as well as observable
events.
It provides support for the backward binary compatibility with the previous model.
Example Java Program to Implement the Event Deligation Model:
[Link]:
import [Link].*;
import [Link].*;
public class TestApp {
public void search() {
// For searching
[Link]("Searching...");
}
public void sort() {
// for sorting
[Link]("Sorting....");
}
static public void main(String args[]) {
TestApp app = new TestApp();
GUI gui = new GUI(app);
}
}
class Command implements ActionListener {
static final int SEARCH = 0;
static final int SORT = 1;
int id;
TestApp app;
public Command(int id, TestApp app) {
[Link] = id;
[Link] = app;
}
public void actionPerformed(ActionEvent e) {
switch(id) {
case SEARCH:
[Link]();
break;
28
case SORT:
[Link]();
break;
}
}
}
class GUI {
public GUI(TestApp app) {
Frame f = new Frame();
[Link](new FlowLayout());
Command searchCmd = new Command([Link], app);
Command sortCmd = new Command([Link], app);
Button b;
[Link](b = new Button("Search"));
[Link](searchCmd);
[Link](b = new Button("Sort"));
[Link](sortCmd);
List l;
[Link](l = new List());
[Link]("Alphabetical");
[Link]("Chronological");
[Link](sortCmd);
[Link]();
[Link]();
}
}
Output:
29
Class constructors
S.N. Constructor & Description
1 EventObject(Object source)
Constructs a prototypical Event.
Class methods
S.N. Method & Description
1 Object getSource()
The object on which the Event initially occurred.
2 String toString()
Returns a String representation of this EventObject.
Methods inherited: This class inherits methods from the following classes:
[Link]
AWT Event Classes:
Following is the list of commonly used event classes.
Sr. Control & Description
No.
1 AWTEvent
It is the root event class for all AWT events. This class and its subclasses
supercede the original [Link] class.
2 ActionEvent
The ActionEvent is generated when button is clicked or the item of a list is
double clicked.
3 InputEvent
The InputEvent class is root event class for all component-level input events.
4 KeyEvent
On entering the character the Key event is generated.
5 MouseEvent
This event indicates a mouse action occurred in a component.
6 TextEvent
The object of this class represents the text events.
7 WindowEvent
The object of this class represents the change in state of a window.
8 AdjustmentEvent
The object of this class represents the adjustment event emitted by Adjustable
objects.
30
9 ComponentEvent
The object of this class represents the change in state of a window.
10 ContainerEvent
The object of this class represents the change in state of a window.
11 MouseMotionEvent
The object of this class represents the change in state of a window.
12 PaintEvent
The object of this class represents the change in state of a window.
1 ActionListener
This interface is used for receiving the action events.
2 ComponentListener
This interface is used for receiving the component events.
3 ItemListener
This interface is used for receiving the item events.
4 KeyListener
This interface is used for receiving the key events.
5 MouseListener
This interface is used for receiving the mouse events.
6 TextListener
This interface is used for receiving the text events.
31
7 WindowListener
This interface is used for receiving the window events.
8 AdjustmentListener
This interface is used for receiving the adjusmtent events.
9 ContainerListener
This interface is used for receiving the container events.
10 MouseMotionListener
This interface is used for receiving the mouse motion events.
11 FocusListener
This interface is used for receiving the focus events.
1. import [Link].*;
2. import [Link].*;
3. public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
4. MouseMotionListenerExample(){
5. addMouse
MotionListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. [Link]([Link]);
32
14. [Link]([Link](),[Link](),20,20);
15. }
16. public void
mouseMoved(MouseEvent e) {}
17.
Output:
itemStateChanged() method
1. import [Link].*;
2. import [Link].*;
3. public class ItemListenerExample implements ItemListener{
4. Checkbox checkBox1,checkBox2;
5. Label label;
6. ItemListenerExample(){
7. Frame f= new Frame("CheckBox Example");
8. label = new Label();
9. [Link]([Link]);
10. [Link](400,100);
33
11. checkBox1 = new Checkbox("C++");
12. [Link](100,100, 50,50);
13. checkBox2 = new Checkbox("Java");
14. [Link](100,150, 50,50);
15. [Link](checkBox1); [Link](checkBox2); [Link](label);
16. [Link](this);
17. [Link]
temListener(this); 18.
[Link](400,4
00);
19. [Link](null);
20. [Link](true);
21. }
22. public void itemStateChanged(ItemEvent e) {
23. if([Link]()==checkBox1)
24. [Link]("C++ Checkbox: "
25. + ([Link]()==1?"checked":"unchecked"));
26. if([Link]()==checkBox2)
27. [Link]("Java Checkbox: "
28. + ([Link]()==1?"checked":"unchecked"));
29. }
30. public static void main(String args[])
31. {
32. new ItemListenerExample();
33. }
34. }
Output:
The Java KeyListener is notified whenever you change the state of key. It is
notified against [Link] KeyListener interface is found in [Link]
package. It has three methods.
34
Methods of KeyListener interface
35
Java Applet
Applet is a small java code which runs on java with the help of web browser.
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content.
Advantage of Applet:
Hierarchy of Applet:
As displayed in the above diagram, Applet class extends Panel. Panel class
extends Container which is the subclass of Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
36
[Link] class provides 1 life cycle methods for an 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.
5. 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.
A special type of Java program that runs in a Web browser is referred to as Applet.
It has less response time because it works on the client-side. It is much secured
executed by the browser under any of the platforms such as Windows, Linux and
Mac OS etc.
There are two types of applets that a web page can contain.
1. Local Applet
2. Remote Applet
1. Local Applet:
Local Applet is written on our own, and then we will embed it into web pages. Local
Applet is developed locally and stored in the local system. A web page doesn't need
the get the information from the internet when it finds the local Applet in the
system. It is specified or defined by the file name or pathname. There are two
attributes used in defining an applet, i.e., the codebase that specifies the path name
and code that defined the name of the file that contains Applet's code.
Syntax:
Example: First, we will create a Local Applet for embedding in a web page. After
that, we will add that Local Applet to the web page.
[Link]
import [Link].*;
import [Link].*;
37
import [Link].*;
import [Link].*;
[Link]([Link]);
} }
2. Remote Applet:
Syntax:
<applet codebase = "[Link] code = "[Link]" width = 120
height =120>
</applet>
38
We don't need to download it. It is available on a remote computer, so we
need to download it to our system.
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file: 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.
[Link]
import [Link];
import [Link];
[Link]("welcome",150,150);
} }
Note: class must be public because its object is created by Java Plugin software that resides
on the browser.
[Link]
<html>
<body>
</applet>
</body>
</html>
//[Link]
import [Link];
import [Link];
39
[Link]("welcome to applet",150,150);
} }
</applet> */
c:\>javac [Link]
c:\>appletviewer [Link]
public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with
the default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with
the specified width and height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used to fill a circular or elliptical arc.
public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
import [Link].*;
40
public class GraphicsDemo extends Applet{
[Link]([Link]);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](70,100,30,30);
[Link](170,100,30,30);
[Link](70,200,30,30);
[Link]([Link]);
[Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
[Link]
<html>
<body>
</applet>
</body>
</html>
41