Professional Documents
Culture Documents
Unit V Gui Programming
Unit V Gui Programming
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications
in java.
Graphical User Interface (GUI) offers user interaction via some graphical components. For
example our underlying Operating System also offers GUI via window,frame,Panel, Button,
Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known as
components. Using these components we can create an interactive user interface for an
application.
GUI provides result to end user in response to raised events.GUI is entirely based events. For
example clicking over a button, closing a window, opening a window, typing something in a
textarea etc. These activities are known as events.GUI makes it easier for the end user to use an
application. It also makes them interesting.
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.
GUI provides graphical icons to interact while the CUI (Character User Interface) offers
the simple text-based interfaces.
GUI makes the application more entertaining and interesting on the other hand CUI does
not.
GUI offers click and execute environment while in CUI every time we have to enter the
command for a task.
1
New user can easily interact with graphical user interface by the visual indicators but it is
difficult in Character user interface.
GUI offers a lot of controls of file system and the operating system while in CUI you
have to use commands which is difficult to remember.
Windows concept in GUI allow the user to view, manipulate and control the multiple
applications at once while in CUI user can control one task at a time.
Limitations of AWT:
It looked different on each platform as AWT was based on native GUI widgets.
Event handling was different. GUI widgets don’t all necessarily support the same events
e.g. if you were listening to a textbox, you might get an event to indicate someone has
typed something at a different time on different systems - like the difference between key
up and key down and ‘contents’ have changed. This made it a nightmare.
Look and feel is very poor when compared to Swing components.
AWT components are heavy weight components.
AWT does not supports a pluggable look and feel.
Components:
Component is an object having a graphical representation that can be displayed on the screen and
that can interact with the user. For examples buttons, checkboxes, list and scrollbars of a
graphical user interface.
Containers:
Ex: JPanel,JFrame,JWindow,JDailog
JWindow is a top-level window that doesn't have any trimmings and can be displayed anywhere
on a desktop. JWindow is a heavyweight component. You usually use JWindow to create pop-up
windows and "splash" screens. JWindow extends AWT's Window class.
2
JFrame is a top-level window that can contain borders and menu bars. JFrame is a subclass
of JWindow and is thus a heavyweight component. You place a JFrame on
a JWindow. JFrame extends AWT's Frame class.
JDialog is a lightweight component that you use to create dialog windows. You can place dialog
windows on a JFrame or JApplet. JDialog extends AWT's Dialog class.
JPanel is the simplest container. It provides space in which any other component can be placed,
including other panels.
3
Exploring swing components:
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.
import javax.swing.*;
class LabelEx extends JFrame
{
LabelEx()
{
setLayout(null);
JLabel l1=new JLabel("Enter Your Email");
l1.setBounds(100,150,150,30);
add(l1);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args)
{
LabelEx l=new LabelEx();
}
}
4
Output:
ImageIcon: Icon is small fixed size picture, typically used to decorate components. ImageIcon is
an implementation of the Icon interface that paints icons from images. Images can be created
from a URL, filename, or byte array.
import javax.swing.*;
class IconEx extends JFrame
{
IconEx()
{
setLayout(null);
Icon pic=new ImageIcon("pic.jpg");
JLabel l1=new JLabel("Pic is",pic,SwingConstants.LEFT);
l1.setBounds(100,150,300,500);
add(l1);
setVisible(true);
setSize(700,700);
}
public static void main(String[] args)
{
5
IconEx l=new IconEx();
}
}
Output:
JTextField: The object of a JTextField class is a text component that allows the editing of a
single line text. It inherits JTextComponent class.
import javax.swing.*;
class TextFieldEx extends JFrame
{
TextFieldEx()
{
setLayout(null);
JTextField tf=new JTextField();
tf.setBounds(100,150,150,30);
6
add(tf);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args)
{
TextFieldEx te=new TextFieldEx();
}
}
Ouput:
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.
import javax.swing.*;
class ButtonEx extends JFrame
{
ButtonEx()
7
{
setLayout(null);
JButton b=new JButton("Login");
b.setBounds(100,150,150,30);
add(b);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args)
{
ButtonEx be=new ButtonEx();
}
}
Output:
import javax.swing.*;
8
import java.awt.event.*;
import java.awt.*;
class ToggleEx extends JFrame implements ItemListener
{
private JToggleButton tb;
ToggleEx()
{
setLayout(new FlowLayout());
tb=new JToggleButton("ON");
add(tb);
setVisible(true);
setSize(500,500);
tb.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
if(tb.isSelected())
{
tb.setText("OFF");
}
else
{
tb.setText("ON");
}
}
public static void main(String[] args)
{
9
ToggleEx te=new ToggleEx();
}
}
Output:
JCheckBox: The JCheckBox 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 ".It inherits JToggleButton class.
Output:
10
JRadioButton: The JRadioButton class is used to create a radio button. It is used to choose one
option from multiple options. It is widely used in exam systems or quiz.
import javax.swing.*;
class RadioEx extends JFrame
{
RadioEx()
{
setLayout(null);
JRadioButton b1=new JRadioButton("Male");
JRadioButton b2=new JRadioButton("Female");
JRadioButton b3=new JRadioButton("Other");
ButtonGroup bg=new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
b1.setBounds(100,150,150,50);
b2.setBounds(100,210,150,50);
b3.setBounds(100,270,150,50);
add(b1);
add(b2);
add(b3);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args)
{
11
RadioEx re=new RadioEx();
}
}
Output:
JComboBox: The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits JComponent class.
import javax.swing.*;
class ComboEx extends JFrame
{
ComboEx()
{
setLayout(null);
String countries[]={"India","Srilanka","Australia","China"};
JComboBox box=new JComboBox(countries);
box.setBounds(100,150,150,30);
12
add(box);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args)
{
ComboEx te=new ComboEx();
}
}
Output:
import javax.swing.*;
class TabbedPaneEx extends JFrame
{
JPanel panel1,panel2,panel3;
JLabel l1,l2,l3;
JTabbedPane pane;
13
TabbedPaneEx()
{
setLayout(null);
panel1=new JPanel();
panel2=new JPanel();
panel3=new JPanel();
l1=new JLabel("This is Anand");
l2=new JLabel("This is Teja");
l3=new JLabel("This is Karthik");
panel1.add(l1);
panel2.add(l2);
panel3.add(l3);
pane=new JTabbedPane();
pane.add("Anand",panel1);
pane.add("Teja",panel2);
pane.add("Karthik",panel3);
add(pane);
pane.setBounds(100,150,200,200);
setVisible(true);
setSize(700,500);
}
public static void main(String[] args)
{
TabbedPaneEx me=new TabbedPaneEx();
}
}
14
Output:
15
JScrollPane: A JscrollPane is used to make scrollable view of a component. When screen size is
limited, we use a scroll pane to display a large component or a component whose size can change
dynamically.
import javax.swing.*;
class ScrollEx extends JFrame
{
JTextArea ta;
JScrollPane pane;
ScrollEx()
{
setLayout(null);
ta=new JTextArea(200,200);
pane=new JScrollPane(ta);
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
pane.setBounds(100,200,200,200);
add(pane);
setVisible(true);
setSize(700,500);
}
public static void main(String[] args)
{
ScrollEx se=new ScrollEx();
}
}
16
Output:
JList: The object of JList class represents a list of text items. The list of text items can be set up
so that the user can choose either one item or multiple items. It inherits JComponent class.
import javax.swing.*;
class ListEx extends JFrame
{
ListEx()
{
setLayout(null);
String hobbies[]={"Playing","Dancing","Sleeping","Eating","Playing with kids"};
JList<String> list=new JList<String>(hobbies);
list.setBounds(100,150,150,150);
add(list);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args)
{
17
ListEx l=new ListEx();
}
}
Output:
Swing Menus:
The JMenuBar class is used to display menubar on the window or frame. It may have several
menus.
The object of JMenu class is a pull down menu component which is displayed from the menu
bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must
belong to the JMenuItem or any of its subclass.
import javax.swing.*;
class MenuEx extends JFrame
{
18
JMenuBar bar;
JMenu menu;
JMenuItem item1,item2,item3,item4;
MenuEx()
{
setLayout(null);
bar=new JMenuBar();
menu=new JMenu("Biryani");
item1=new JMenuItem("Chicken Biryani");
item2=new JMenuItem("Mutton Biryani");
item3=new JMenuItem("Fish Biryani");
item4=new JMenuItem("Vegitable Biryani");
menu.add(item1);
menu.add(item2);
menu.add(item3);
menu.add(item4);
bar.add(menu);
setJMenuBar(bar);
setVisible(true);
setSize(700,500);
}
public static void main(String[] args)
{
MenuEx me=new MenuEx();
}
}
19
Output:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.GridBagLayout
java.awt.CardLayout
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 frame or
window. The BorderLayout provides five constants for each region:
20
public static final int CENTER
import javax.swing.*;
import java.awt.*;
class BorderEx extends JFrame
{
JButton b1,b2,b3,b4,b5;
BorderLayout b;
BorderEx()
{
b=new BorderLayout();
setLayout(b);
b1=new JButton("Button 1");
b2=new JButton("Button 2");
b3=new JButton("Button 3");
b4=new JButton("Button 4");
b5=new JButton("Button 5");
add(b1,"North");
add(b2,"Center");
add(b3,"West");
add(b4,"East");
add(b5,"South");
setVisible(true);
setSize(400,400);
}
public static void main(String[] args)
{
BorderEx be=new BorderEx();
21
}
}
Output:
GridLayout:
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Constructors of GridLayout class:
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.
import javax.swing.*;
import java.awt.*;
class GridEx extends JFrame
{
JButton b1,b2,b3,b4,b5,b6;
GridLayout g;
GridEx()
{
g=new GridLayout(3,2);
22
setLayout(g);
b1=new JButton("Button 1");
b2=new JButton("Button 2");
b3=new JButton("Button 3");
b4=new JButton("Button 4");
b5=new JButton("Button 5");
b6=new JButton("Button 6");
add("1",b1);
add("2",b2);
add("3",b3);
add("4",b4);
add("5",b5);
add("6",b6);
setVisible(true);
setSize(400,400);
}
public static void main(String[] args)
{
GridEx be=new GridEx();
}
}
Output:
23
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.
import javax.swing.*;
import java.awt.*;
class FlowEx extends JFrame
{
JButton b1,b2,b3,b4,b5;
FlowLayout f;
FlowEx()
{
f=new FlowLayout();
setLayout(f);
b1=new JButton("Button 1");
b2=new JButton("Button 2");
b3=new JButton("Button 3");
b4=new JButton("Button 4");
b5=new JButton("Button 5");
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
setVisible(true);
setSize(400,400);
}
24
public static void main(String[] args)
{
FlowEx be=new FlowEx();
}
}
Output:
Event Handling:
The delegation event model, which defines standard and consistent mechanisms to generate and
process events. Its concept is quite simple: a source generates an event and sends it to one or
more listeners. In this scheme, the listener simply waits until it receives an event. Once an event
is received, the listener processes the event and then returns. The advantage of this design is that
the application logic that processes events is cleanly separated from the user interface logic that
generates those events.
In the delegation event model, listeners must register with a source in order to receive an event
notification. This provides an important benefit: notifications are sent only to listeners that want
to receive them.
Events
In the delegation model, an event is an object that describes a state change in a source. It can be
generated as a consequence of a person interacting with the elements in a graphical user
interface. Some of the activities that cause events to be generated are pressing a button, entering
a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user
operations could also be cited as examples.
Events may also occur that are not directly caused by interactions with a user interface. For
example, an event may be generated when a timer expires, a counter exceeds a value, a software
25
or hardware failure occurs, or an operation is completed. You are free to define events that are
appropriate for your application.
Event Sources
Asource is an object that generates an event. This occurs when the internal state of that object
changes in some way. Sources may generate more than one type of event. Asource must register
listeners in order for the listeners to receive notifications about a specific type of event. Each
type of event has its own registration method. Here is the general form:
A source must also provide a method that allows a listener to unregister an interest in a specific
type of event. The general form of such a method is this:
Event Classes
The package java.awt.event defines many types of events that are generated by various user
interface elements. Table shows several commonly used event classes and provides a brief
description of when they are generated. Commonly used constructors and methods in each class
are described in the following sections.
26
Event Listeners:
A listener is an object that is notified when an event occurs. It has two major requirements. First,
it must have been registered with one or more sources to receive notifications about specific
types of events. Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event. For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved
Registration Methods:
For registering the component with the Listener, many classes provide the registration methods.
For example:
Button
MenuItem
27
public void addActionListener(ActionListener a){}
TextField
TextArea
Checkbox
Choice
List
import java.awt.*;
import java.awt.event.*;
TextField tf;
AEvent(){
//create components
28
tf=new TextField();
tf.setBounds(60,50,170,20);
b.setBounds(100,120,80,30);
//register listener
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
tf.setText("Welcome");
new AEvent();
29
Output:
//package org.kits.cse;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
JLabel l1;
public Ax(){
30
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setLayout(new GridBagLayout());
l1=new JLabel();
l1.setFont(f);
l1.setForeground(Color.BLUE);
l1.setAlignmentX(Component.CENTER_ALIGNMENT);
l1.setAlignmentY(Component.CENTER_ALIGNMENT);
add(l1);
addMouseListener(this);
setVisible(true);
l1.setText("Mouse Exited");
l1.setText("Mouse Entered");
l1.setText("Mouse Released");
31
}
l1.setText("Mouse Pressed");
l1.setText("Mouse Clicked");
Ax a=new Ax();
Output:
32
Adapter Classes
Java provides a special feature, called an adapter class, that can simplify the creation of event
handlers in certain situations. An adapter class provides an empty implementation of all methods
in an event listener interface. Adapter classes are useful when you want to receiveand process
only some of the events that are handled by a particular event listener interface.
You can define a new class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ), which are the methods defined by the MouseMotionListener interface. If you
were interested in only mouse drag events, then you could simply extend MouseMotionAdapter
and override mouseDragged( ). The empty implementation of mouseMoved( ) would handle the
mouse motion events for you.
The following example demonstrates an adapter. It displays a message in the status bar of an
applet viewer or browser when the mouse is clicked or dragged. However, all other mouse events
are silently ignored. The program has three classes. AdapterDemo extends Applet. Its init( )
method creates an instance of MyMouseAdapter and registers that object to receive notifications
of mouse events. It also creates an instance of MyMouseMotionAdapter and registers that object
33
to receive notifications of mouse motion events. Both of the constructors take a reference to the
applet as an argument.
MyMouseAdapter extends MouseAdapter and overrides the mouseClicked( ) method. The other
mouse events are silently ignored by code inherited from the MouseAdapter class.
MyMouseMotionAdapter extends MouseMotionAdapter and overrides the mouseDragged( )
method. The other mouse motion event is silently ignored by code inherited from the
MouseMotionAdapter class.
Applets:
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
Hierarchy of Applet
34
Lifecycle of Java Applet:
Applet is initialized.
Applet is started.
Applet is painted.
Applet is stopped.
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.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to start
the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
35
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
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.
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.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
g.drawString("welcome",150,150);
36
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html
<html>
<body>
</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;
g.drawString("welcome to applet",150,150);
/*
37
<applet code="First.class" width="300" height="300">
</applet>
*/
c:\>javac First.java
c:\>appletviewer First.java
Applet Application
Small Program Large Program
Used to run a program on client Browser Can be executed on stand alone computer system
Applet is portable and can be executed by any Need JDK, JRE, JVM installed on client
JAVA supported browser. machine.
Applet applications are executed in a Restricted Application can access all the resources of the
Environment computer
Applets are created by extending the Applications are created by writing public static
java.applet.Applet void main(String[] s) method.
Applet application has 5 methods which will be
Application has a single start point which is main
automatically invoked on occurance of specific
method
event
Example:
import java.awt.*;
import java.applet.*;
38
Applet Security Issues:
Applets are treated as untrusted because they are developed by somebody and placed on some
unknown Web server. When downloaded, they may harm the system resources or steal
passwords and valuable information available on the system. As applets are untrusted, the
browsers come with many security restrictions. Security policies are browser dependent.
Browser does not allow the applet to access any of the system resources (applet is permitted to
use browser resources, infact, applet execution goes within the browser only).
Applets are not permitted to use any system resources like file system as they are
untrusted and can inject virus into the system.
Applets cannot read from or write to hard disk files.
Applet methods cannot be native.
Applets should not attempt to create socket connections
Applets cannot read system properties
Applets cannot use any software available on the system (except browser execution area)
Cannot create objects of applications available on the system by composition
A great benefit of passing applet parameters from HTML pages to the applets they call is
portability. If you pass parameters into your Java applets, they can be portable from one web
page to another, and from one web site to another. On the other hand, if you don't pass
parameters into a Java applet, how will the applet know what font to use? Simple - you hardwire
it into the Java source code.
The listing below shows the source code for the sample HTML file we created for this article,
including the applet tag shown. We name this file AppletParameterTest.html.
<HTML>
<HEAD>
<TITLE>Java applet example - Passing applet parameters to Java applets</TITLE>
39
</HEAD>
<BODY>
<APPLET CODE="AppletParameterTest.class" WIDTH="400" HEIGHT="50">
<PARAM NAME="font" VALUE="Dialog">
<PARAM NAME="size" VALUE="24">
<PARAM NAME="string" VALUE="Hello, world ... it's me. :)">
</APPLET>
</BODY>
</HTML>
As you can see, the HTML file identifies the Java applet that we want to load -
AppletParameterTest.class using an APPLET tag. Then, the only thing we need to do to pass
parameters to the applet are to include the name and value of the desired parameters in
<PARAM> tags. These names and values can be whatever we want - whatever makes sense for
your applet. As a final note, notice that the <PARAM> tags are enclosed within the <APPLET>
tags.
So far we've seen to create the HTML code that (1) invokes a Java applet using an applet tag, and
(2) passes parameters to the applet. Next, let's look at the Java applet code needed to read the
parameters being passed to it. The next listing shows the Java code for the ParamTest.java file.
import java.applet.*;
import java.awt.*;
/**
* A Java applet parameter test class.
* Demonstrates how to read applet parameters.
*/
public class AppletParameterTest extends Applet {
40
public void paint(Graphics g) {
41