Unit 1 - Creating GUI
Unit 1 - Creating GUI
Unit 1
Creating GUI
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
(UI) 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.
Introducing Swing
When Java 1.0 was introduced, it contained a class library, which Sun called the Abstract
Window Toolkit (AWT), for basic GUI programming. The basic AWT library deals with
user interface elements by delegating their creation and behaviour to the native GUI
toolkit on each target platform (Windows, Solaris, Macintosh, and so on).
This peer-based approach worked well for simple applications. User interface elements
such as menus, scrollbars, and text fields can have subtle differences in behavior on
different platforms. Moreover, some graphical environments do not have as rich a
collection of user interface components as does Windows or the Macintosh. As a result,
GUI applications built with the AWT simply did not look as nice as native Windows or
Macintosh applications, nor did they have the kind of functionality that users of those
platforms had come to expect. More depressingly, there were different bugs in the AWT
user interface library on the different platforms.
In 1996, Netscape created a GUI library they called the IFC (Internet Foundation Classes)
that used an entirely different approach. User interface elements, such as buttons, menus,
and so on, were painted onto blank windows. The only functionality required from the
underlying windowing system was a way to put up windows and to paint on the window.
Thus, Netscape’s IFC widgets looked and behaved the same no matter which platform the
program ran on. Sun worked with Netscape to perfect this approach, creating a user
interface library with the code name ―Swing.‖ Swing was available as an extension to
Java 1.1 and became a part of the standard library in Java SE 1.2.
Swing is now the official name for the non-peer-based GUI toolkit. Swing is part of the
Java Foundation Classes (JFC). The benefits of using swing components are:
Swing has a rich and convenient set of user interface elements.
Swing has few dependencies on the underlying platform; it is therefore less prone
to platform-specific bugs.
Swing gives a consistent user experience across platforms.
Still, the third plus is also a potential drawback: If the user interface elements look the
same on all platforms, they look different from the native controls, so users will be less
familiar with them. Swing solves this problem in a very elegant way. Programmers
writing Swing programs can give the program a specific ―look-and-feel.‖
Page 1
Creating GUI Unit 1
Creating a Frame
A top-level window (that is, a window that is not contained inside another window) is
called a frame in Java. The AWT library has a class, called Frame, for this top level. The
Swing version of this class is called JFrame and extends the Frame class. The JFrame is
one of the few Swing components that is not painted on a canvas. Thus, the decorations
(buttons, title bar, icons, and so on) are drawn by the user’s windowing system, not by
Swing. A simple program that displays an empty fame on the screen is given below.
import javax.swing.*;
import java.awt.*;
public class SimpleFrame
{
public static void main(String[] args)
{
EventQueue.invokeLater(()->
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300,200);
f.setVisible(true);
});
}
}
The Swing classes are placed in the javax.swing package. By default, a frame has a rather
useless size of 0 × 0 pixels. We sets the size to 300 × 200 pixels using setSize method and
make it visible using setVisible method.
There are two technical issues that we need to address in every Swing program. First, all
Swing components must be configured from the event dispatch thread, the thread of
control that passes events such as mouse clicks and keystrokes to the user interface
components. The following code fragment is used to execute statements in the event
dispatch thread:
EventQueue.invokeLater(() ->
{
statements
Page 2
Creating GUI Unit 1
});
Next, we define what should happen when the user closes the application’s frame. For
this particular program, we want the program to exit. To select this behavior, we use the
statement
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
In other programs with multiple frames, you would not want the program to exit just
because the user closes one of the frames. By default, a frame is hidden when the user
closes it, but the program does not terminate.
After scheduling the initialization statements, the main method exits. Note that exiting
main does not terminate the program – just the main thread. The event dispatch thread
keeps the program alive until it is terminated.
If we run this program, we can see the title bar and the surrounding decorations, such as
resize corners, are drawn by the operating system and not the Swing library. If you run
the same program in Windows, GTK, and the Mac, the frame decorations will be
different. The Swing library draws everything inside the frame.
The JFrame class itself has only a few methods for changing how frames look. Of
course, through the magic of inheritance, most of the methods for working with frames
come from the various superclasses of JFrame. The figure below shows inheritance
hierarchy for JFrame class.
Page 3
Creating GUI Unit 1
void setBounds(int x, int y, int width, int height) – moves and resizes this
component.
Dimension getSize(), void setSize(Dimension d) – gets or sets the size property of
this component.
Some common methods from java.awt.Window
void toFront() – shows this window on top of any other windows.
void toBack() – moves this window to the back of the stack of windows on the
desktop and rearranges all other visible windows accordingly.
boolean isLocationByPlatform(), void setLocationByPlatform(boolean b) – gets
or sets the locationByPlatform property. When the property is set before this
window is displayed, the platform picks a suitable location.
Some common methods from javax.awt.Frmae
boolean isResizable(), void setResizable(boolean b) – gets or sets the resizable
property. When the property is set, the user can resize the frame.
String getTitle(), void setTitle(String s) – gets or sets the title property that
determines the text in the title bar for the frame.
Image getIconImage(), void setIconImage(Image image) – gets or sets the
iconImage property that determines the icon for the frame. The windowing system
may display the icon as part of the frame decoration or in other locations.
boolean isUndecorated(), void setUndecorated(boolean b) – gets or sets the
undecorated property. When the property is set, the frame is displayed without
decorations such as a title bar or close button. This method must be called before
the frame is displayed.
int getExtendedState(), void setExtendedState(int state) – gets or sets the
extended window state. The state is one of
Frame.NORMAL
Frame.ICONIFIED
Frame.MAXIMIZED_HORIZ
Frame.MAXIMIZED_VERT
Frame.MAXIMIZED_BOTH
Page 4
Creating GUI Unit 1
Event Handling
Event handling is of fundamental importance to programs with a graphical user interface.
Any operating environment that supports GUIs constantly monitors events such as
keystrokes or mouse clicks. The operating environment reports these events to the
programs that are running. Each program then decides what, if anything, to do in
response to these events.
Java uses AWT event model for handling events. This 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: an event source generates
an event and sends it to one or more event listeners. You can designate any object to be
Page 5
Creating GUI Unit 1
an event listener. The listener simply waits until it receives an event. Once an event is
received, the listener processes the event and then returns.
Event sources have methods that allow you to register event listeners with them. For
example, the method that registers a keyboard event listener is called addKeyListener.
We can also use removeKeyListener method to remove keyboard listener. When an
event happens to the source, the source sends a notification of that event to all the listener
objects that were registered for that event.
Different event sources can produce different kinds of events. For example, a button can
send ActionEvent objects, whereas a window can send WindowEvent objects. All event
classes that are handled by delegation model in Java derive from java.util.EventObject
class.
To sum up, here’s an overview of how event handling in the AWT works:
A listener object is an instance of a class that implements a special interface called
a listener interface.
An event source is an object that can register listener objects and send them event
objects.
The event source sends out event objects to all registered listeners when that event
occurs.
The listener objects will then use the information in the event object to determine
their reaction to the event.
In the program below, whenever the user clicks the button, the JButton object creates an
ActionEvent object and listener object is notified. The actionPerformed method in the
listener object is called receiving the event object as a parameter.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EventDemo
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300,200);
SimplePanel p = new SimplePanel();
f.add(p);
f.setVisible(true);
});
}
}
class SimplePanel extends JPanel
{
private final JButton b;
private final JTextField t;
Page 6
Creating GUI Unit 1
public SimplePanel()
{
b = new JButton("Ok");
t = new JTextField(8);
MyEventListener me = new MyEventListener();
b.addActionListener(me);
add(b);
add(t);
}
private class MyEventListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
t.setText("Hello World!");
}
}
}
The table below shows the most important AWT listener interfaces, events and event
sources.
Interface Methods Parameter / Events
Accessors Generated By
ActionListener actionPerformed ActionEvent AbstractButton
getActionCommand JComoBox
getModifiers JTextField
Timer
AdjustmentListener adjustmentValueChanged AdjustmentEvent JScrollbar
getAdjustable
getAdjustmentType
getValue
ItemListener itemStateChanged ItemEvent AbstractButton
getItem JComboBox
getItemSelectable
getStateChange
FocusListener focusGained FocusEvent Component
focusLost isTemporary
KeyListener keyPressed KeyEvent Component
keyReleased getKeyChar
keyTyped getKeyCode
getKeyModifiersText
getKeyText
isActionKey
MouseListener mousePressed MouseEvent Component
mouseReleased getClickCount
mouseEntered getX
mouseExited getY
mouseClicked getPoint
translatePoint
MouseMotionListener mouseDragged MouseEvent Component
Page 7
Creating GUI Unit 1
mouseMoved
MouseWheelListener mouseWheelMoved MouseWheelEvent Component
getWheelRotation
getScrollAmount
WindowListener windowClosing WindowEvent Window
windowOpened getWindow
windowIconified
windowDeiconified
windowClosed
windowActivated
windowDeactivated
WindowFocusListener windowGainedFocus WindowEvent Window
windowLostFocus getOppositeWindow
WindowStateListener windowStateChanged WindowEvent Window
getOldState
getNewState
Java also 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 receive and 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. An interface such as ActionListener that has only a single method does not
need an adapter class. Some commonly used adapter classes in java.awt.event package
are: ComponentAdapter, ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter,
MouseMotionAdapter, and WindowAdapter. For example,
class SimplePanel extends JPanel
{
private final JTextField t;
public SimplePanel()
{
t = new JTextField(8);
MyEventListener me = new MyEventListener();
addMouseListener(me);
add(t);
}
private class MyEventListener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
t.setText("Hello World!");
}
}
}
Page 8
Creating GUI Unit 1
Layout Management
A layout manager automatically arranges your components inside a container using some
type of algorithm. The layout manager is set by the setLayout method. If no call to
setLayout is made, then the default layout manager is used. The setLayout method has the
following general form:
void setLayout(LayoutManager m)
Here, m 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 manager that
best fits your application.
FlowLayout
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 space 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.LEADING,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));
For example,
class SimplePanel extends JPanel
{
private final JButton b;
private final JTextField t;
public SimplePanel()
{
b = new JButton("Ok");
t = new JTextField(8);
setLayout(new FlowLayout(FlowLayout.LEFT));
add(b);
add(t);
Page 9
Creating GUI Unit 1
}
}
BorderLayout
This layout manager 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.
Page 10
Creating GUI Unit 1
p2.add(t);
add(BorderLayout.NORTH,p1);
add(BorderLayout.SOUTH,p2);
}
}
BoxLayout
It lays out components either in a row or in a column. The BoxLayout class has only one
constructor.
BoxLayout(Container target, int axis) – creates a box layout with the specified container
that needs to be laid out and the axis to lay out components along. The value of axis can
be one of the following:
BoxLayout.X_AXIS – Components are laid out horizontally from left to right.
BoxLayout.Y_AXIS – Components are laid out vertically from top to bottom.
For example,
setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
GridLayout
It lays out components in a two-dimensional grid. The constructors supported by
GridLayout 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
column.
GridBagLayout
The grid bag layout is the mother of all layout managers. You can think of a grid bag
layout as a grid layout without the limitations. In a grid bag layout, the rows and columns
can have variable sizes. You can join adjacent cells to make room for larger components.
The components need not fill the entire cell area, and you can specify their alignment
within cells.
To describe the layout to the grid bag manager, use the following procedure:
1. Create an object of type GridBagLayout. You don’t need to tell it how many rows
and columns the underlying grid has. Instead, the layout manager will try to guess
it from the information you give it later.
2. Set this GridBagLayout object to be the layout manager for the container.
3. For each component, create an object of type GridBagConstraints. Set field values
of the GridBagConstraints object to specify how the components are laid out
within the grid bag.
Page 11
Creating GUI Unit 1
4. Finally, add each component with its constraints by using the call add(component,
constraints)
Here’s an example of the code needed.
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints constraints = new GridBagConstraints();
constraints.weightx = 100;
constraints.weighty = 100;
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
constraints.gridheight = 1;
panel.add(component, constraints);
The gridx, gridy, gridwidth, and gridheight constraints define where the component is
located in the grid. The gridx and gridy values specify the column and row positions of
the upper left corner of the component to be added. The gridwidth and gridheight values
determine how many columns and rows the component occupies. The grid coordinates
start with 0.
You always need to set the weight fields (weightx and weighty) for each area in a grid
bag layout. If you set the weight to 0, the area never grows or shrinks beyond its initial
size in that specified direction. If you set them to 100, the area grows or shrinks in that
specified direction.
If you don’t want a component to stretch out and fill the entire area, set the fill constraint.
You have four possibilities for this parameter: the valid values are
GridBagConstraints.NONE, GridBagConstraints.HORIZONTAL,
GridBagConstraints.VERTICAL, and GridBagConstraints.BOTH.
constraints.fill = GridBagConstraints.NONE;
If the component does not fill the entire area, you can specify where in the area you want
it by setting the anchor field. The valid values are GridBagConstraints.CENTER (the
default), GridBagConstraints.NORTH, GridBagConstraints.NORTHEAST,
GridBagConstraints.EAST, and so on.
constraints.anchor = GridBagConstraints.NORTH;
You can surround a component with additional blank space by setting the insets field of
GridBagConstraints. Set the left, top, right, and bottom values of the Insets object to the
amount of space that you want to have around the component. For example,
constraints.insets = new Insets(10,10,10,10);
The ipadx and ipady values set the internal padding. These values are added to the
minimum width and height of the component. For example,
constraints.ipadx = 20;
constraints.ipady = 20;
Page 12
Creating GUI Unit 1
GroupLayout
GroupLayout is a layout manager that was developed for GUI builders such as Matisse,
the GUI builder provided with the NetBeans IDE.
GroupLayout works with the horizontal and vertical layouts separately. The layout is
defined for each dimension independently. You do not need to worry about
the vertical dimension when defining the horizontal layout, and vice versa, as the layout
along each axis is totally independent of the layout along the other axis. Each component
needs to be defined twice in the layout. If you forget to do this, GroupLayout will
generate an exception.
GroupLayout uses two types of arrangements – sequential and parallel, combined with
hierarchical composition.
1. With sequential arrangement, the components are simply placed one after another
along one axis. The position of each component is defined as being relative to the
preceding component.
2. The second way places the components in parallel – on top of each other in the
same space. They can be baseline-, top-, or bottom-aligned along the vertical axis.
Along the horizontal axis, they can be left-, right-, or center-aligned if the
components are not all the same size.
Usually, components placed in parallel in one dimension are in a sequence in the other,
so that they do not overlap. What makes these two arrangements powerful is that they can
be nested hierarchically. For this purpose GroupLayout defines layout groups. A group
is either sequential or parallel and may contain components, other groups, and gaps. The
size of a sequential group is the sum of the sizes of the contained elements, and the size
of a parallel group corresponds to the size of the largest element. Defining a layout means
defining how the components should be grouped by combining the sequential and parallel
arrangements. For example,
class SimplePanel extends JPanel
{
private final JButton b1;
private final JTextField t1;
public SimplePanel()
{
b1 = new JButton("Ok");
t1 = new JTextField(16);
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(b1)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(t1)
.addContainerGap(238, Short.MAX_VALUE))
);
Page 13
Creating GUI Unit 1
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(b1)
.addComponent(t1))
.addContainerGap(266, Short.MAX_VALUE))
);
}
}
Page 14
Creating GUI Unit 1
Labels
A label displays a single line of read-only text, an image or both text and an image.
Labels 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) – creates a label that contains the icon specified by
image using the alignment specified by align.
JLabel(String str, Icon image, int align) – creates a label that contains both icon
and string using the alignment specified by align.
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.
String getText(), void setText() – gets or sets the text of this label.
Icon getIcon(), void setIcon() – gets or sets the icon of this label.
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. Several
of its constructors are shown here:
JTextField() – constructs a new empty JTextField with 0 column width.
JTextField(int cols) – constructs a new empty JTextField with the specified
number of columns.
JTextField(String s) – constructs a new JTextField with an initial string.
JTextField(String s, int cols) – constructs a new JTextField with an initial string
and the specified number of columns.
Some of its common methods are:
int getColumns(), void setColumns(int cols) – gets or sets the number of columns
that this text field should use.
Some common methods inherited from javax.swing.JTextComponent class are given
below.
String getText(), void setText(String text) – gets or sets the text of this text
component.
boolean isEditable(), void setEditable(boolean b) – gets or sets the editable
property that determines whether the user can edit the content of this text
component.
Some common methods inherited from javax.swing.JComponent class are given below.
void revalidate() – causes the position and size of a component to be recomputed.
Page 15
Creating GUI Unit 1
Password Fields
Password fields are a special kind of text field. To prevent from seeing your password,
the characters that the user enters are not actually displayed. Instead, each typed character
is represented by an echo character, typically an asterisk (*). Swing supplies a
JPasswordField class that implements such a text field. This class is immediate child of
JTextField class.
Some common constructors of JPasswordField are:
JPasswordField() – constructs a new password field with null starting text string,
and 0 column width.
JPasswordField(String text) – constructs a new password field initialized with the
specified text.
JPasswordField(int colums) – constructs a new password field with the specified
number of columns.
JPasswordField(String text, int cols) – constructs a new password field with the
specified text and columns.
Some common methods of JPasswordField are:
char getEchoChar(), void setEchoChar(char echo) – gets or sets the echo character
for this password field.
char[] getPassword() - returns the text contained in this password field.
Text Area
If you need to collect user input that is more than one line long, you can use the
JTextArea component. When you place a text area component in your program, a user
can enter any number of lines of text, using the Enter key to separate them. Each line
ends with a '\n'. Most commonly used constructors are given below:
JTextArea() – constructs a new text area with null starting text string, and 0 row
and column width.
JTextArea(String text) – constructs a new text area initialized with the specified
text.
JTextArea(int rows, int columns) – constructs a new text area with the specified
rows and columns.
JTextArea(String text, int rows, int columns) – constructs a new text area with
specified text, rows and columns.
Some common methods are:
int getColumns(), void setColumns(int columns) – gets or sets the number of
columns of this text area component.
Page 16
Creating GUI Unit 1
int getRowss(), void setRows(int columns) – gets or sets the number of rows of
this text area component.
void setLineWrap(boolean wrap) – avoid clipping long lines by turning on line
wrapping. This wrapping is a visual effect only; the text in the document is not
changed—no automatic '\n' characters are inserted into the text.
void append(String newText) – appends the given text to the end of the text
already in the text area.
You can also use all the methods inherited from javax.swing.JTextComponent,
javax.swing.JComponent, and java.awt.Component classes as with JTextField.
Buttons
The most widely used component is the push button. A push button is a component that
contains a label and generates an event when it is pressed. The JButton class provides the
functionality of a push buttons. It allows an icon, a string, or both to be associated with
the push button. Some useful constructors are:
JButton() – creates an empty button.
JButton(Icon icon) – creates a button that contains icon as a label.
JButton(String text) – create a button that contains text as a label.
JButton(String text, Icon icon) – creates a button that contains text and icon as
label.
There are several methods you will use when working with JButton. Some of them are
given below:
Icon getIcon() – retrives icon associated with the button.
String getText() – retrives text associated with the button.
boolean isSelected() – returns true if the button is selected.
void setIcon(Icon icon) – sets icon as its label.
void setText(String text) – sets text as its label.
Check Boxes
A check box is a control that is used to turn an option on or off. It consists of a small box
that can either contain a check mark or not. There is a label associated with each check
box that describes what option the check box represents. You can change the state of a
check box by clicking on it. Check boxes can be used individually or as part of a group.
Check boxes are objects of the JCheckBox class. Some useful constructors are:
JCheckBox() – creates a checkbox whose label is blank. The state of the check
box is unchecked.
JCheckBox(String str) – creates a checkbox whose label is specified by str. The
state of the check box is unchecked.
JCheckBox(String str, boolean state) – creates a checkbox whose label is
specified by str. If state is true, the check box is initially checked; otherwise it is
cleared.
JCheckBox(Icon i) – creates a checkbox with an icon i. The state of the check box
is unchecked.
Page 17
Creating GUI Unit 1
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() – Creates an unselected radio button with no text.
JRadioButton(Icon i) – Creates an unselected radio button with specified icon.
JRadioButton(Icon i, boolean state) – Creates an unselected radio button with
specified icon and selected state.
JRadioButton(String text) – Creates an unselected radio button with specified
text.
JRadioButton(String text, boolean state) – Creates a radio button with the
specified text and selected state.
JRadioButton(String text, Icon i) – Creates an unselected radio button with
specified text and icon.
JRadioButton(String text, Icon i, boolean state) – Creates an unselected radio
button with specified text, icon, and state.
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);
Page 18
Creating GUI Unit 1
Combo Boxes
Combo box is a combination of a text field and a drop-down list. A combo box normally
displays one entry. However, it can also display a drop-down list that allows a user to
select a different entry. You can also type your selection into the text field. Swing
provides a combo box through the JComboBox class. Some of its constructors are:
JComboBox() – Creates a JComboBox with a default data model.
JComboBox(Object[] items) – Creates a JComboBox that contains the elements in
the specified array.
Some of its commonly used methods are:
void addItem(Object anObject) – used to add an item to the item list.
void removeItem(Object anObject) – used to delete an item to the item list.
void removeAllItems() – used to remove all the items from the list.
void removeItemAt(int index) - removes the item at an index.
void setEditable(boolean b) – used to determine whether the JComboBox is
editable.
int getSelectedIndex() – returns the index of selected item in the list that
Object getSelectedItem() – returns the current selected item.
Object getItemAt(int index) – returns the list item at the specified index.
int getItemCount() – returns the number of items in the list.
Menu Bars
A menu bar at the top of a window contains the names of the pull-down menus. Clicking
on a name opens the menu containing menu items and submenus. When the user clicks on
a menu item, all menus are closed and a message is sent to the program.
Swing provides a menu bar through the JMenuBar class. The dropdowns within that bar
are JMenu objects. JMenus can be nested within a JMenu to provide sub-menus. Each
Menu is a collection of the widgets JMenuItem, JRadioButtonMenuItem,
JCheckBoxMenuItem and JSeparator. When the user selects a menu, an action event is
triggered. You need to install an action listener for each menu item.
To add a menu bar to a top-level container, create a JMenuBar object, populate it with
menus, and then call setJMenuBar method. For example,
JFrame frame = new JFrame("Menu bar demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenuItem newItem = new JMenuItem("New");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");
fileMenu.add(newItem);
fileMenu.add(openItem);
Page 19
Creating GUI Unit 1
fileMenu.add(saveItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
frame.setJMenuBar(menuBar);
frame.setSize(200, 200);
frame.setVisible(true);
Dialog Boxes
You usually want separate dialog boxes to pop up to give information to, or get
information from, the user. Swing has a convenient JOptionPane class that lets you put
up a simple dialog without writing any special dialog box code. The JOptionPane has
four static methods to show these simple dialogs:
showMessageDialog – Show a message and wait for the user to click OK
showConfirmDialog – Show a message and get a confirmation (like OK/Cancel)
showOptionDialog – Show a message and get a user option from a set of options
showInputDialog – Show a message and get one line of user input
The icon on the left side of the dialog box depends on one of five message types:
ERROR_MESSAGE
INFORMATION_MESSAGE
WARNING_MESSAGE
QUESTION_MESSAGE
PLAIN_MESSAGE
For each dialog type, you can specify a message. This message can be a string, an icon, a
user interface component, or any other object.
The buttons at the bottom of the dialog box depend on the dialog type and the option
type. When calling showMessageDialog and showInputDialog, you get only a standard
set of buttons. When calling showConfirmDialog, you can choose among four option
types:
DEFAULT_OPTION
YES_NO_OPTION
YES_NO_CANCEL_OPTION
OK_CANCEL_OPTION
With the showOptionDialog you can specify an arbitrary set of options. You supply an
array of objects for the options.
The return values of these functions are as follows:
showMessageDialog – None
showConfirmDialog – An integer representing the chosen option
showOptionDialog – An integer representing the chosen option
showInputDialog – The string that the user supplied or selected
The showConfirmDialog and showOptionDialog return integers to indicate which button
the user chose. For the option dialog, this is simply the index of the chosen option or the
value CLOSED_OPTION if the user closed the dialog instead of choosing an option. For
the confirmation dialog, the return value can be one of the following:
Page 20
Creating GUI Unit 1
OK_OPTION
CANCEL_OPTION
YES_OPTION
NO_OPTION
CLOSED_OPTION
For example,
int selection = JOptionPane.showConfirmDialog(parent, "Message", "Title",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if(selection == JOptionPane.OK_OPTION)
…………………….
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 applets
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 subclass
of the JApplet class. It is the extended version of java.applet.Applet that adds support for
the swing components. The following diagram shows the inheritance hierarchy of the
JApplet class.
Page 21
Creating GUI Unit 1
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++.
Page 22
Creating GUI Unit 1
frees up the resources it has held. Remember the methods: stop() and destroy().
The applet is initialized, started, stopped and destroyed. These four processes define the
life cycle of an applet. Here are the descriptions of the methods.
init(): This method is 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.
Page 23
Creating GUI Unit 1
Running an Applet:
There are two ways of running the applet. The first one is to execute the applet within the
java compatible web browsers. The second way is using the tool appletviewer.
Regardless of the above method you must write a short HTML file as follows:
<applet code = "AppletDemo " width = "200 " height = "100 ">
</applet>
You can save the HTML file as name of your choice (say fisrtapplet.html).
Now give the command appletviewer firstapplet.html and see the result.
Page 24
Creating GUI Unit 1
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
displayed.
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.
Exercises
1. Write a GUI application to calculate sum and difference of two numbers. Use two
text fields for input and third text field for output. Your program should display sum
if user clicks sum button and difference if subtract button is clicked.
2. Write a GUI application to calculate simple interest. Use text fields for inputs and
output. Use mouseClick method to generate the result.
3. Write a GUI application that receives three numeric values as input and then displays
the largest of the three numbers. Use text fields for input and output. The result
should be displayed when a button is pressed and a checkbook is checked.
4. Use adapter class to handle events in question number 2.
5. Write Java applets for the question no. 1 above.
Page 25