0% found this document useful (0 votes)
4 views39 pages

Java AWT and Swing GUI Programming Guide

Java AWT (Abstract Window Toolkit) is an API for developing GUI applications in Java, offering platform-dependent heavyweight components like buttons and text fields. In contrast, Java Swing, built on top of AWT, provides lightweight, platform-independent components and follows the MVC architecture. The document also includes examples and explanations of various AWT and Swing components, layout management, and event handling.

Uploaded by

tagoregangadari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views39 pages

Java AWT and Swing GUI Programming Guide

Java AWT (Abstract Window Toolkit) is an API for developing GUI applications in Java, offering platform-dependent heavyweight components like buttons and text fields. In contrast, Java Swing, built on top of AWT, provides lightweight, platform-independent components and follows the MVC architecture. The document also includes examples and explanations of various AWT and Swing components, layout management, and event handling.

Uploaded by

tagoregangadari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

GUI Programming with java The AWT Class hierarchy

Java AWT(Abstract Window Toolkit) is an API to develop GUI or window-based applications in


java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system.
AWT is heavyweight i.e. its components are using the resources of OS.
The [Link] package provides classes for AWT API such as TextField , Label, TextArea ,
RadioButton , CheckBox , Choice, List etc.
Java AWT Hierarchy The hierarchy of Java AWT classes are given.
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.
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.
Panel
The Panel is the container that doesn't contain title bar and menu bars.
It can have other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars.
It can have other components like button, textfield etc.
Useful Methods of Component class
Method Description
public void add(Component c) inserts a component on this component

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.
Java AWT Example To create simple awt example, you need a frame.
There are two ways to create a frame in AWT.
 By extending Frame class(inheritance)
 By creating the object of Frame class(association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class.
Here, we are showing Button component on the Frame.
[Link].*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
[Link](30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[])
{
First f=new First();
}}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example
that sets the position of the awt button.
Java Swing
Java Swing tutorial 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.
Unlike AWT, Java Swing provides platform-independent and lightweight
components.
The [Link] package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc
Difference between AWT and Swing
No. Java AWT Java Swing
1 AWT components dependent. are Java swing components are platform
platform- independent.

2 AWT components are heavyweight Swing components are lightweight.


3 AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel

4 AWT provides less Swing. components Swing provides more powerful


than components such as tables, lists, scroll
panes, color chooser, tabbed pane etc.

5 AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data,
view represents presentation and
controller acts as an interface between
model andview.
Commonly used Methods of Component class
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) Sets the layout manager for the component.
public void setLayout(LayoutManager m) Sets the visibility of the component. It is by
default false
Hierarchy of Java Swing classes The hierarchy of java swing API is given below
Java Swing Examples
There are two ways to create a frame:
o By creating the object of Frame class(association)
o By extending Frame class(inheritance)
We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example Let's see a simple swing example where we are creating one button
and adding it on the JFrame object inside the main() method.
File: [Link]
Import [Link].*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame(); //creating instance of JFrame JButton
b=new JButton("click"); //creating instance of JButton
[Link](130,100,100,40); //x axis, y axis, width,
height [Link](b);//adding button in JFrame
[Link](400,500);//400 width and 500 height
[Link](null);//using no layout managers
[Link](true);//making the frame visible
}
}
Containers
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 aGUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
JFrame Example
Import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JFrameExample
{
public static void main(String s[])
{
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
[Link](new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
[Link]("Button");
[Link](label);
[Link](button);
[Link](panel);
[Link](200, 300);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}}
JApplet As we prefer Swing to AWT.
Now we can use JApplet that can have all the controls of swing.
The JApplet class extends the Appletclass.
Example of EventHandling in JApplet:
Import [Link].*;
import [Link].*;
import [Link].*;
public class EventJApplet extends JApplet implements ActionListener
{
JButton b;
JTextField tf;
public void init()
{
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);
}
public void actionPerformed(ActionEvent e)
{
[Link]("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is invoked only
once. [Link]
[Link]
<html>
<body>
<applets code="[Link]" width="300"height="300“>
</applets>
<body>
<html>
JDialog
The JDialog 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 Dialogclass. Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration
Let's see the declaration for [Link] class.
public classJDialog extends Dialog implements WindowConstants,Accessible,RootPaneContainer
Commonly used Constructors:
Constructor Description
JDialog() It is used to create a modeless dialog
without a title and without a specified
Frame owner.
JDialog(Frame owner) It is used to create a modeless dialog
with specified Frame as its owner and
an empty title.
JDialog(Frame owner, String title, boolean modal) It is used to create a dialog with the
specified title, owner Frame
andmodality.
Java JDialog Example
Import [Link].*;
Import [Link].*;
Import [Link].*;
Output:
public class DialogExample
{
private static JDialog d;
DialogExample()
{
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
[Link]( new FlowLayout() );
JButton b = new JButton ("OK");
[Link]( new ActionListener());
{
public void actionPerformed(ActionEvent e)
{
Dialog [Link](false);
}
}
[Link](new JLabel ("Click button to continue."));
[Link](b);
[Link](300,300);
[Link](true);
}
public static void main(String args[])
{
New DialogExample();
}
}
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.
It doesn't have title bar.
JPanel class declaration
public class JPanel extends JComponent implements Accessible Java JPanel Example
Import [Link].*;
Import [Link].*;
public class PanelExample
{
PanelExample() Output:
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
[Link](40,80,200,200);
[Link]([Link]);
JButton b1=new JButton("Button 1");
[Link](50,100,80,30);
[Link]([Link]);
JButton b2=new JButton("Button 2");
[Link](100,100,80,30);
[Link]([Link]);
[Link](b1);
[Link](b2);
[Link](panel);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
newPanelExample(); } }
Overview of some Swing
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
JButton class declaration
Let'ssee the declaration for [Link].
JButton class.
1. public class JButton extends AbstractButton implements Accessible
Java JButton Example
[Link].*;
public class ButtonExample
output
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true);
}}
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.
JLabel class declaration
Let's see the declaration for [Link] class.
1. public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description
JLabel() Creates a JLabel instance with no
image and with an empty string for
the title.
JLabel(String s) Creates a JLabel instance with the
specified text.
JLabel(Icon i) Creates a JLabel instance with the
specified image
JLabel(String s, horizontalAlignment) Icon i, int Creates a JLabel instance with the
horizontalAlignment) specified text, image, and
horizontal alignment.
Commonly used Methods:
Methods Description
String getText() t returns the text string that a label displays.
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 Xaxis.
Icon getIcon() It returns the graphic image that the label
display
int getHorizontalAlignment() It returns the alignment of the label's
contents along the X axis.
Java JLabel Example
import [Link].*;
class LabelExample
{ OUTPUT
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
[Link](50,50, 100,30);
l2=new JLabel("Second Label.");
[Link](50,100, 100,30);
[Link](l1);
[Link](l2);
[Link](300,300);
[Link](null);
[Link](true);
}
}
JTextField
The object of a JTextField class is a text component that allows the editing of a single line text.
It inherits JTextComponent class.
JTextField class declaration Let's see the declaration for [Link].
JTextField class.
1. public class JTextField extends JTextComponent implements SwingConstants
Java JTextField Example
[Link].*; Example
classTextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
[Link](50,100, 200,30);
t2=new JTextField("AWT Tutorial");
[Link](50,150, 200,30);
[Link](t1);
[Link](t2);
[Link](400,400);
f.s etLayout(null);
[Link](true);
}}
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
JTextArea class declaration
Let's see the declaration for [Link] class.
1. public class JTextArea extends JTextComponent
Java JTextArea Example
import [Link].*; Output
public class TextAreaExample
{
TextAreaExample()
{
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
[Link](10,30, 200,200);
[Link](area);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String args[])
{ newTextAreaExample();
}}
Simple Java Applications
import [Link];
[Link]; output
public class Example extends Jframe
{
public Example()
{
setTitle("Simple example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
Example ex = new Example();
[Link](true);
}
}
Layout Management
Java LayoutManagers

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


LayoutManager is an interface that is implemented by all the classes of layoutmanagers.

BorderLayout
The BorderLayout provides five constants for each region:

[Link] 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 thecomponents.


o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between thecomponents.
Example of GridLayout class [Link](b9);
import [Link].*; [Link](new GridLayout(3,3));
import [Link].*; //setting grid layout of 3 rows and 3 columns
public class MyGridLayout [Link](300,300);
{ f.s etVisible(true);
JFramef; MyGridLayout(){ f=new JFrame(); }
JButton b1=new JButton("1"); public static void main(String[] args)
JButton b2=new JButton("2"); {
JButton b3=new JButton("3"); new MyGridLayout();
JButton b4=new JButton("4"); }
JButton b5=new JButton("5"); }
JButton b6=new JButton("6"); Output
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
[Link](b1);
[Link](b2);
[Link](b3);
[Link](b4);
[Link](b5);
[Link](b6)
;[Link](b7)
;[Link](b8);
Java FlowLayout
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.

Fields of FlowLayout class

[Link] static final intLEFT


2. public static final intRIGHT
3. public static final intCENTER
4. public static final intLEADING
5. public static final intTRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and verticalgap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default
5 unit horizontal and verticalgap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and verticalgap.
Example of FlowLayout class [Link](300,300);
import [Link].*; f.s etVisible(true);
import [Link].*; }
public class MyFlowLayout public static void main(String[] args)
{ {
JFramef; newMyFlowLayout();
MyFlowLayout() }
{ }
f=new JFrame();
JButton b1=new JButton("1"); Output
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
[Link](b1);
[Link](b2)
;[Link](b3)
;[Link](b4);
[Link](b5);
[Link](new FlowLayout([Link]));
//setting flow layout of right alignment
Event Handling
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event.
For example, click on button, dragging mouse etc.
The [Link] package provides many event classes and Listener interfaces for event
handling.
Types of Event
The events can be broadly classified into two categories:
• Foreground Events - Those events which require the direct interaction of user .
They 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.
• BackgroundEvents-Those events that require the interaction of end use rare 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.
Java Uses the Delegation Event Model to handle the events.
This model defines the standard mechanism to generate and handle the events.
Let's have a brief introduction to this model
The Delegation Event Model has the following key participants namely:
• 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.
• Listener - It is also known as event handler.
Listener 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.
Event classes and Listener interfaces:
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Implement the Listener interface and overrides its methods
2. Register the component with theListener For registering the component with the Listener,
many classes provide the registration methods.
For example:
o Button
o public void addActionListener(ActionListenera){}
o MenuItem
o public void addActionListener(ActionListenera){}
o TextField
o public void addActionListener(ActionListenera){}
o public void addTextListener(TextListenera){}
o TextArea
o public void addTextListener(TextListenera){}
o Checkbox
o public void addItemListener(ItemListenera){}
o Choice
o public void addItemListener(ItemListenera){}
o List
o public void addActionListener(ActionListenera){}
o public void addItemListener(ItemListenera){}
EventHandling Codes: We can put the event handling code into one of the following places: 1.
Sameclass 2. Otherclass 3. Annonymousclass
Example of event handling within class:
Import [Link].*;
Import [Link].*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
AEvent()
{
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
[Link](this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
[Link]("Welcome");
}
public static void main(String args[])
{
newAEvent();
}}
public void setBounds(int xaxis, int yaxis, int width, int height);
have been used in the above example that sets the position of the component it may be button,
textfield etc.
Java event handling by implementing ActionListener
Import [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
Aevent()
{ //create components
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30); //register listener
[Link](this); //passing current instance
//add components and set size, layout and visibility
add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
[Link]("Welcome");
}
public static void main(String args[])
{
newAEvent();
Java MouseListener Interface The Java MouseListener is notified whenever you change the state of
mouse.
It is notified against MouseEvent.
The MouseListener interface is found in [Link] package. It has five methods.
Methods of MouseListener interface The signature of 5 methods found in MouseListener interface are
given below:
1. public abstract void mouseClicked(MouseEvente);
2. public abstract void mouseEntered(MouseEvente);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvente);
6. Java MouseListener Example
Impor [Link].*;
import [Link].*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l;
MouseListenerExample()
{
addMouseListener(this);
l=new Label();
[Link](20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
[Link]("MouseClicked");
}
public void mouseEntered(MouseEvent e)
{
[Link]("MouseEntered");
} public void mouseExited(MouseEvent e)
{
[Link]("Mouse Exited");
} public void mousePressed(MouseEvent e)
{
[Link]("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
[Link]("Mouse Released");
}
public static void main(String[] args)
{
new MouseListenerExample();
}
}
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key.
It is notified against KeyEvent.
The KeyListener interface is found in [Link] package.
It hasthree methods. Methods of KeyListener interface
The signature of 3 methods found in KeyListener interface are given below:
1. public abstract void keyPressed(KeyEvente);
2. public abstract void keyReleased(KeyEvente);
3. public abstract void keyTyped(KeyEvente);
Java KeyListener Example
import [Link].*; i
import [Link].*;
public class KeyListenerExample extends Frame implements KeyListener{ Label l;
TextArea area;
KeyListenerExample()
{
l=new Label();
[Link](20,50,100,20);
area=new TextArea();
[Link](20,80,300, 300);
[Link](this);
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e)
{
[Link]("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
[Link]("Key Released");
}
public void keyTyped(KeyEvent e)
{
[Link]("Key Typed");
}
public static void main(String[] args)
{
new KeyListenerExample();
}
}
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces.
If you inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
Adapterclass Listenerinterface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener

Java WindowAdapter Example 1


import [Link].*;
Import [Link].*;
public class AdapterExample
{
Frame f;
AdapterExample()
{
f=new Frame("Window Adapter");
[Link] WindowListener(new WindowAdapter ()
{
public void windowClosing(WindowEvent e)
{
[Link]();
}
}
f.s etSize(400,400);
[Link](null);
[Link](true);
}
public static void main(String[] args)
{
new AdapterExample();
}
}
Applets
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 There are many
advantages of applet.
They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Osetc.
Drawback of Applet
o Plug in is required at client browser to execute applet.
Lifecycle of Java Applet Hierarchy of Applet
1. Applet isinitialized.
2. Applet isstarted.
3. Applet ispainted.
4. Applet isstopped.
5. Applet isdestroyed.
Lifecycle methods for Applet:
The [Link] class 4 life cycle methods and
[Link] class provides
1 life cycle methods for an applet.
[Link] class
For creating any applet [Link] class must be inherited.
It provides 4 life cycle methods of applet.
6. 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.
[Link] class The Component class provides
1 life cycle method of applet.
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.
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.
1. //[Link]
import [Link];
[Link];
public class First extends Applet
{
public void paint(Graphics g)
{
[Link]("welcome",150,150);
}
}
/*
<applet code="[Link]" width="300" height="300”>
</applet>*/
To execute the applet by applet viewer tool, write in command prompt:
c:\>javac [Link] c:\>appletviewer [Link]
Difference between Applet and Application programming
Parameter in Applet We can get any information from the HTML file as a parameter.
For this purpose, Applet class provides a method named getParameter().
Syntax: 1. publicString getParameter(String parameterName)
Example of using parameter in Applet:
import [Link];
import [Link];
public class UseParam extends Applet
{
public void paint(Graphics g)
{
Strings tr=getParameter("msg");
[Link](str,50,50);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300"height="300”>
<param name="msg" value="Welcome toapplet“>
</applet>
</body>
</html>

You might also like