Chap-2 Swing
Chap-2 Swing
Chap-2 Swing
Introduction
A graphical user interface (GUI) presents a pictorial interface to a program. A GUI gives
a program a distinctive “look” add “feel”. GUI provides programs a set of user interface
components. This reduces the time that users require to learn a program and increases
their ability to use the program in a productive manner.
GUIs are built from GUI components (sometimes called controls or widgets – short
for window gadgets). A GUI component is an object with which the user interacts via the
mouse, the keyboard or another form of input, such as voice recognition.
Swing
The classes that create the GUI components are part of the Swing GUI components from
package javax.swing. Most Swing components are written, manipulated and displayed
completely in Java (so-called pure Java components).
The original GUI components from the Abstract Windowing Toolkit package java.awt
(also called the AWT) are tied directly to the local platform’s graphical user interface ca-
pabilities. When a Java program with an AWT GUI executes on different Java platforms,
the program’s GUI components display differently on each platform.
The Swing components allow the programmer to specify a uniform look and feel
across all platforms. In addition, Swing enables programs to provide a custom look and
feel for each platform or even to change the look and feel while the program is running.
Swing components are often referred to as lightweight components since they are
completely written in Java. AWT components that are tied to the local platform are corre-
spondingly called heavyweight components – they rely on the local platform’s windowing
system to determine their functionality and their look and feel. Several Swing compo-
nents are still heavyweight components. In particular, subclasses of java.awt.Frame
(such as JFrame) that display windows on the screen and subclasses of java.applet.Ap-
plet (such as JApplet) still require direct interaction with the local windowing system. As
such, heavyweight Swing GUI components are less flexible than many of the lightweight
components.
Example:
import javax.swing.*;
public class SwingExample extends JFrame{
public SwingExample() {
super("Simple swing example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello World");
getContentPane().add(label);
pack();
setVisible(true);
}
}
Swing Components
With the exception of top-level containers, all Swing components whose name begins
with “J” descend from the JComponent class. For example, JButton, JTextField, JLabel
etc. all inherit from JComponent. To include a component in a Window, you must add it
to the window. To do this, you must first create an instance of the desired component and
then add it to a window by calling add(), which is defined by Container class. There are
several forms of add() method. The following form is most common:
Component add(Component compObj)
Here compObj is an instance of the component that you want to add. Once a control has
been added, it will automatically visible whenever its parent window is displayed.
Sometimes you will want to remove a control from a window when the control is no
longer needed. To do this, call remove(). This method is also defined by Container. It has
the following general form:
void remove (Component obj)
Here, obj is a reference to the control you want to remove. You can remove all con-
trols by calling removeAll(). It has the following general form:
void remove ()
Some most commonly used swing components are discussed below:
Icons and Labels
Icons are encapsulated by the ImageIcon class, which paints an icon from an image. The
two types of constructors are shown here:
ImageIcon(String filename) – uses the image in the file named filename.
ImageIcon(URL url) – uses image in the resource identified by url.
A label displays a single line of read-only text, an image or both text and an image. La-
bels are defined with class JLabel. Some of its useful constructors are:
JLabel() – creates a blank label.
JLabel(String str) – creates a label that contains the string specified by str.
JLabel(String str, int align) – creates a label that contains the string specified by str using
the alignment specified by align. The align argument is JLabel.LEFT, JLabel.RIGHT,
JLabel.CENTER, JLabel.LEADING, or JLabel.TRAILING.
JLabel(Icon image) – creates a label that contains the icon specified by image.
JLabel(Icon image, int align
JLabel(String str, Icon image, int aling)
There are several methods you will use when working with JLabel. Some of them are
given below. These methods can read and write icon and text associated with the label.
Icon getIcon()
String getText()
Vod setIcon()
Void setText()
Text Fields
Text fields allow the user to enter one line text and edit using the arrow keys, cut and
paste keys, and mouse selection. Text fields are defined with the class JTextField. Sev-
eral of its constructors are shown here:
JTextField()
JTextField(int cols)
JTextField(String s)
JTextField(String s, int cols)
Here, s is the string to be initially presented, and cols is the number of columns in the text
field. Some of its methods are given below:
There are several methods you will use when working with JCheckBox. Some of them
are given below:
Icon getIcon() – retrives icon associated with the check box.
String getText() – retrives text associated with the check box.
void setIcon(Icon icon) – sets icon as its label.
void setText(String text) – sets text as its label.
void setSelected(boolean state) - if state is true, the check box is checked; otherwise it is
cleared.
boolean isSelected() – retrieves state (true or false) of the check box.
Radio Buttons
It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These check boxes are often
called radio buttons. Radio buttons are supported by JRadioButton class. Several of its
constructors are shown here:
JRadioButton()
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button and s is the text specified. If state is true, the button is
initially selected. Otherwise, it is not. You can use all the above methods discussed with
check boxes for radio buttons.
Radio buttons must be configured into a group. Only one of the buttons in that group
can be selected at any time. The ButtonGroup class is instantiated to create a button
group. Its default constructor [ButtonGroup()] is invoked for this purpose. Elements are
then added to the button group via the following method void add(AbstractButton ab).
For example,
JRadioButton rb1 = new JRadioButton("A");
JRadioButton rb2 = new JRadioButton("B");
ButtonGroup bg = new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
Layout Managers
A layout manager automatically arranges your controls within a window by using some
type of algorithm. The layout manager is set by the setLayout() method. If no call to set-
Layout() is made, then the default layout manager is used. The setLayout() method has
the following general form:
void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout manager. Java has several predefined
layout manager classes. Some of them are described below. You can use the layout man-
ager that best fits your application.
FlowLayout
It is the default layout manager. FlowLayout implements a simple layout style, which is
similar to how words flow in a text editor. Components are laid out from the upper left
corner, left to right, and top to bottom. When no more components fit on a line, the next
one appears on the next line. A small is left between each component, above and below,
as well as left and right. Here are the constructors for FlowLayout:
FlowLayout()
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centers components and leaves five pixels
of space between each component. For example,
setLayout(new FlowLayout());
The second form lets you specify how each line is aligned. Valid values for how are:
FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT, FlowLayout.LEAD-
ING, and FlowLayout.TRAILING. For example,
setLayout(new FlowLayout(FlowLayout.LEFT));
The third constructor allows you to specify the horizontal and vertical space left between
components in horz and vert respectively. For example,
setLayout(new FlowLayout(FlowLayout.LEFT,20,30));
BorderLayout
It has four narrow, fixed-width components at the edges and one large area in the center.
The four sides are referenced to as north, south, east, and west. The middle area is called
the center. Here are the constructors defined by BorderLayout:
BorderLayout() – creates a default border layout.
BorderLayout(int horz, int vert) – allows you to specify the horizontal and vertical space
left between components in horz and vert, respectively.
BorderLayout defines four constants that specify regions: BorderLayout.CENTER, Bor-
derLayout.EAST, BorderLayout.NORTH, BorderLayout.SOUTH, and BorderLay-
out.WEST.
When adding components, we will use these constants with the following form of add().
void add(Component compObj, Object region)
For example,
getContentPane().add(label,BorderLayout.NORTH);
GridLayout
It lays out components in a two-dimensional grid. The constructors supported by Grid-
Layout are:
GridLayout() – creates a single-column grid layout.
GridLayout(int numRows, int numCols) – creates a grid layout with the specified number
of rows and columns.
GridLayout(int numRows, int numCols, int horz, int vert) – also allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
Either numRows or numColumns can be zero. Specifying numRows as zero allows for
unlimited length columns and specifying numColumns as zero allows for unlimited
length rows. Components are added from first row to last row and first column to last col-
umn.
Using Insets
Sometimes you will want to leave a small amount of space between the container that
holds your components and the window that contains it. To do this, override the
getInsets() method that is defined by Container. This function returns an Insets object
that contains the top, bottom, left, and right inset to be used when the container is dis-
played. The constructor for Insets is shown here:
Insets(int top, int left, int bottom, int right)
The values passed in top, left, bottom, and right specify the amount of space between the
container and its enclosing window. The getInsets() method has this general form:
Insets getInsets()
When overriding this method, we must return a new Insets object that contains the inset
spacing you desire. For example,
public Insets getInsets() {
return new Insets(10,10,20,30);
}
Handling Events
The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events. This concept
is quite simple: a source generates an event and sends it to one or more listeners. The lis-
tener simply waits until it receives an event. Once an event is received, the listener pro -
cesses the event and then returns.
In order to receive an event notification, listeners must register with an event source.
Hence, 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 graphi-
cal 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, clicking the
mouse etc. 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 ex-
ceeds a value, software or hardware failure occurs, or an operation is completed.
At the root of the Java event class hierarchy is EventObject class which is the super-
class for all event classes. AWTEvent, a subclass of EventObject, is a superclass of all
AWT events that are handled by the delegation model. The table below lists the most im -
portant of these event classes and provides a brief description of when they are generated.
Event Class Description
ActionEvent Generated when a button is pressed, a list item is double-clicked,
or a menu item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized, or be-
comes visible.
ContainerEvent Generated when a component is added to or removed from a con-
tainer.
FocusEvent Generated when a component gains or losses keyboard focus.
ItemEvent Generated when a check box or list item is clicked; also occurs
when a choice selection is made or a checkable menu item is se-
lected or deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed,
or released; also generated when the muse enters or exits a com-
ponent.
MouseWheelEvent Generated when the mouse wheel is moved.
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, de-
iconified, iconified, opened, or quit.
Event Sources
A source 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. The ta-
ble below lists some of the event sources that can generate events.
Event Source Description
Button Generates action events when button is pressed.
Checkbox Generates item events when the check box is selected or dese-
lected.
Choice Generates item events when the choice is changed
List Generates action events when an item is double-clicked; gener-
Advanced Java
10programming
Compiled by: Ramesh Bhatta Page 11
ItemListener Defines one method to recognize when a check box or list item
is clicked, when a choice selection is made, or when a checkable
menu item is selected or disselected.
void itemStateChanged(ItemEvent ie)
KeyListener Defines three methods to recognize when a key is presses, re-
leased, or typed.
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
MouseListener Defines five methods to recognize when the mouse is clicked,
enters a component, exits a component, is pressed, or is re-
leased.
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
MouseMotionListener Defines two methods to recognize when the mouse is dragged or
moved.
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
MoseWheelListener Defines one method to recognize when the mouse wheel is
moved.
void mouseWheelMoved(MouseWheelEvent mwe)
TextListener Defines one method to recognize when a text value changes.
void textChanged(TextEvent te)
WindowFocusListener Defines two methods to recognize when a window gains or
looses input focus.
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
WindowListener Defines seven methods to recognize when a window is acti-
vated, closed, deactivated, deiconified, iconified, opened, or
quit.
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
An Example
import javax.swing.*;
import java.awt.*;
Advanced Java
11programming
Compiled by: Ramesh Bhatta Page 12
import java.awt.event.*;
public class SwingExample extends JFrame implements ActionLis-
tener {
private JTextField t1, t2, t3;
public SwingExample() {
super("SwingExample");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel l1 = new JLabel("First Value:");
JLabel l2 = new JLabel("Second Value:");
JLabel l3 = new JLabel("Result:");
t1 = new JTextField(8);
t2 = new JTextField(8);
t3 = new JTextField(8);
JButton b1 = new JButton("Add");
JButton b2 = new JButton("Subtract");
b1.addActionListener(this);
b2.addActionListener(this);
Container cp = getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.LEFT));
cp.add(l1);
cp.add(t1);
cp.add(l2);
cp.add(t2);
cp.add(b1);
cp.add(b2);
cp.add(l3);
cp.add(t3);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String s1, s2, s;
int x, y, z;
s1 = t1.getText();
s2 = t2.getText();
if(s1.equals(""))
x = 0;
else
x = Integer.parseInt(s1);
if(s2.equals(""))
y = 0;
else
y = Integer.parseInt(s2);
if(ae.getActionCommand() == "Add")
z = x + y;
else
z = x - y;
s = String.valueOf(z);
t3.setText(s);
}
Advanced Java
12programming
Compiled by: Ramesh Bhatta Page 13
}
}
Applets
Applet is a Java program that runs in the applet viewer or web browser that supports
Java. The main difference between normal Java applications and applets is that in applet
there is no main method unlike the standalone applications in Java.
We can embed applets into Web pages in two ways. One, we can write our own ap-
plets and embed them into Web pages. Second, we can download an applet from a remote
computer system and then embed it into a Web page.
An applet developed locally and stored in a local system is known as a local applet.
A remote applet is that which is developed by someone else and stored on a remote
computer connected to the Internet. If our system is connected to the Internet, we can
download the remote applet onto our system and run it.
Every applet in Java that uses swing components is implemented by creating a sub-
class of the JApplet class. It is the extended version of java.applet.Applet that adds sup-
port for the swing components. The following diagram shows the inheritance hierarchy of
the JApplet class.
Java.lang.Object
Java.awt.Component
Java.awt.Container
Java.awt.Panel
Java.applet.Applet
Javax.swing.JApplet
Advanced Java
13programming
Compiled by: Ramesh Bhatta Page 14
Applets do not use the main( ) method for initiating the execution of the code. Ap-
plets when loaded, automatically call certain methods of Applet class to start and ex-
ecute the applet code.
Unlike standalone applications, applets cannot be run independently. They are run
from inside a Web page using special feature known as HTML tag.
Applets cannot read from or write to the files in the local computer.
Applets cannot communicate with other servers on the network.
Applets cannot run any program from the local computer.
Applets are restricted from using libraries from other languages such as C or C++.
Applet Lifecycle
Advanced Java
14programming
Compiled by: Ramesh Bhatta Page 15
Every Java applet inherits a set of default behaviors from the JApplet class. These
behaviors are described below:
Loading the Applet
This phase creates an instance of the applet, initializes the applet and starts running. Re-
member two methods: init( ) and start( ).
Leaving and Returning to the Applet's Page
When the user leaves the page the browser stops the applet. When the user returns to the
page, the browser starts the applet. So is true for minimize and maximize. Remember
methods stop( ) and start( ).
Reloading the Applet
Some browsers let the user reload applets, which consists of unloading the applet and
then loading it again. Before an applet is unloaded, it's given the chance to stop itself and
then to perform a final cleanup, so that the applet can release any resources it holds. After
that, the applet is unloaded and then loaded again.
Quitting the Browser
When the user quits the browser the applet stops and frees up the resources it has held.
Remember the methods: stop( ) and destroy( ).
The applet is loaded, started, stopped and destroyed. These four processes define the life
cycle of an applet. Here are the descriptions of the methods.
init: This method called at the initialization of the applet and called automatically
only once.
start: This method is automatically called after init method. It is also called whenever
user returns to the page containing the applet after visiting other pages.
stop: This method is automatically called whenever the user moves away from the
page containing applets.
destroy: This method is called when the browser shuts down normally and it is called
only once.
Advanced Java
15programming
Compiled by: Ramesh Bhatta Page 16
Advanced Java
16programming
Compiled by: Ramesh Bhatta Page 17
Advanced Java
17programming
Compiled by: Ramesh Bhatta Page 18
Advanced Java
18programming
Compiled by: Ramesh Bhatta Page 19
else
z = x - y;
s = String.valueOf(z);
t3.setText(s);
}
}
Security Restrictions
The implementation of the security policies differs from browser to browser. Also,
security policies are subject to change. Current browsers impose the following
restrictions on any applet that is loaded over the network:
An applet cannot load libraries or define native methods.
It cannot ordinarily read or write files on the host that's executing it.
It cannot make network connections except to the host that it came from.
It cannot start any program on the host that's executing it.
It cannot read certain system properties.
Applet Capabilities
Applets possess some capabilities that applications do not have. Here are some other
things that current browsers and other applet viewers let applets do:
Applets can usually make network connections to the host they came from.
Applets running within a Web browser can easily cause HTML documents to be dis-
played.
Applets can invoke public methods of other applets on the same page.
Applets that are loaded from the local file system (from a directory in the user's
CLASSPATH) have none of the restrictions that applets loaded over the network do.
Advanced Java
19programming