Unit 1 - GUI Programming
Unit 1 - GUI Programming
Unit 1
GUI Programming
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.”
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
});
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.
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 JButton b;
private JTextField t;
public SimplePanel()
{
b = new JButton("Ok");
t = new JTextField(8);
add(b);
add(t);
}
}
}
To draw rectangles, we use drawRect(x1, y1, w, h) method and to draw string we use
drawString(“String”, x1, y1) and so on. The drawings using Graphics class methods are
very limited. For example, you cannot vary the line thickness and cannot rotate the
shapes.
Java SE 1.2 introduced the Java 2D library, which implements a powerful set of
graphical operations. To draw shapes in the Java 2D library, you need to obtain an object
of the Graphics2D class. This class is a subclass of the Graphics class.
The Java 2D library organizes geometric shapes in an object-oriented fashion. In
particular, there are classes to represent lines (Line2D), rectangles (Rectangle2D) and
ellipses (Ellipse2D) in java.awt.geom package.
These classes all implement the Shape interface. To draw a shape, you first create an
object of a class that implements the Shape interface and then call the draw method
of the Graphics2D class. For example, to draw a rectangle, we can write a program as
follows:
class SimplePanel extends JPanel
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
Rectangle2D floatRect = new Rectangle2D.Float (10, 15.5F, 52.5F, 60.0F);
g2d.draw(floatRect);
}
}
By using the Java 2D library, you keep your options open – you can later enhance your
drawings with some of the many tools that the Java 2D library supplies. Graphics class
method used integer pixel coordinates; the Java 2D shapes use floating-point coordinates.
In many cases, it is a great convenience because it allows you to specify your shapes in
coordinates that are meaningful to you (such as millimeters or inches) and then translate
to pixels. The designers of the 2D library have supplied two versions of each shape class:
one with float coordinates and one with double coordinates.
Rectangle2D Class
The Rectangle2D class an abstract class with two concrete subclasses, which are also
static inner classes: Rectangle2D.Float and Rectangle2D.Double as
shown in the figure below.
Point2D Class
There is a Point2D class with subclasses Point2D.Float and
Point2D.Double. Here is how to make a point object.
Point2D p = new Point2D.Double (10, 20);
The Point2D class is very useful - it is more object-oriented to work with Point2D
objects than with separate x- and y- values. Many constructors and methods accept
Point2D parameters. It is suggested that you use Point2D objects when you can –
they usually make geometric computations easier to understand.
Ellipse2D Class
For drawing the elliptical shapes we need to provide the coordinates of bounding
rectangles. Then Elliptical shapes are drawn by jointing the mid points of the sides of the
rectangle. It is similar to Graphics class. For example,
Ellipse2D e = new Ellipse2D.Double (150, 200, 100, 50);
constructs an ellipse that is bounded by a rectangle with the top-left corner at (150, 200),
Width 100 and height 50.
RoundRectangle2D Class
For drawing the round edges rectangular shapes we need to provide the top left corner,
width and height, and the x- and y-dimension of the corner area that should be rounded.
For example,
RoundRectangle2D r = new RoundRectangle2D.Double(150, 200, 100, 50, 20, 20);
produces a rounded rectangle with circles of radius 20 at each of the corners.
Arc2D Class
To construct an arc, you specify the bounding box, followed by the start angle and the
angle swept out by the arc and the closure type, one of Arc2D.OPEN, Arc2D.PIE, or
Arc2D.CHORD. Its general form is:
Arc2D a = new Arc2D.Double (x, y, width, height, startAngle, arcAngle, closureType);
OR
Arc2D a = new Arc2D.Float (x, y, width, height, startAngle, arcAngle, closureType);
For Example
Arc2D a = new Arc2D.Double(10, 10, 200, 200, 45, 180, Arc2D.CHORD);
QuadCurve2D Class
The Java 2D package supplies quadratic curves. Quadratic curves are specified by two
end points and one control point. Moving the control points changes the shape of the
curves. Its general form is:
QuadCurve2D q = new QuadCurve2D.Double(startX, startY, controlX, controlY, endX,
endY);
For example,
QuadCurve2D q = new QuadCurve2D.Float(10,10,50,300,200,200);
CubicCurve2D Class
The Java 2D package supplies cubic curves. Cubic curves are specified by two end points
and two control point. Moving the control points changes the shape of the curves. Its
general form is:
CubicCurve2D c = new CubicCurve2D.Double(startX, startY, control1X, control1Y,
control2X, control2Y, endX, endY);
For example,
CubicCurve2D q = new CubicCurve2D.Float(10,10,100,50,100,300,200,200);
We define colors with the Color class. The java.awt.Color class offers
predefined constants for the 13 standard colors listed in following table
Black Green Red
Blue lightGray White
Cyan Magenta Yellow
darkGray Orange Gray
Pink
For example,
Graphics2D g2d=(Graphics2D)g;
g2d.setPaint(Color.red);
Rectangle2D r1 = new Rectangle2D.Float (10.0F, 25.0F,
22.5F, 20.0F);
g2d.draw(r1);
We can specify a custom color by creating a Color object by its red, green, and blue
components. Using a scale of 0–255 (that is, one byte) for the redness, blueness, and
greenness, we call the Color constructor like this:
new Color(int redness, int greenness, int blueness)
For example,
g2d.setPaint(new Color(0, 128, 128));
Filling Shapes
You can fill the interiors of closed shapes (such as rectangles or ellipses) with a color.
Simply call fill instead of draw. For example,
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(Color.red);
Rectangle2D r1 = new Rectangle2D.Float (10.0F, 25.0F, 22.5F, 20.0F);
g2d.fill(r1);
import java.awt.*;
public class ListFonts
{
public static void main(String[] args)
{
GraphicsEnvironment ge=
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames=ge.getAvailableFontFamilyNames();
for (int i = 0; i < fontNames.length; i++)
System.out.println(fontNames[i]);
}
}
To draw characters in a font, you must first create an object of the class Font. You
specify the font name, the font style, and the point size. Here is an example of how you
construct a Font object.
Font f = new Font ("Helvetica", Font.BOLD, 14);
You specify the style (plain, bold, italic, or bold italic) by setting the second Font
constructor argument to one of the following values:
Font.PLAIN
Font.BOLD
Font.ITALIC
Font.BOLD + Font.ITALIC
To use a font that you have created, you must select it using setFont method. Its general
form is:
void setFont(Font fontObj)
For example,
Font f = new Font ("Helvetica", Font.BOLD, 44);
setFont(f);
g.drawString("Hello",100,100);
To obtain information about the currently selected font, we use getFont method. Its
general form is:
Font getFont()
Displaying Images
Once images are stored in local files or someplace on the Internet, you can read them into
a Java application and display them on Graphics objects. There are many ways of reading
images. Here, we use the ImageIcon class that you already saw:
Image img = new ImageIcon(filename).getImage();
Now the variable image contains a reference to an object that encapsulates the image
data. You can display the image with the drawImage methods of the Graphics class as
given below.
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
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:
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;
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
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,
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);
}
}
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.
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.
4. Finally, add each component with its constraints by using the call to
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;
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))
);
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))
);
}
}
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.
• void setFont(Font f) – sets the font of this component.
Some common methods inherited from java.awt.Component class are given below.
• void validate() – recomputes the position and size of a component. If the
component is a container, the positions and sizes of its components are
recomputed.
• Font getFont() – gets the font of this component.
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.
• int getRows(), void setRows(int columns) – gets or sets the number of rows of
this text area component.
• boolean 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.
• JCheckBox(Icon i, boolean state) – creates a checkbox with an icon i. If state is
true, the check box is initially checked; otherwise it is cleared.
• JCheckBox(String, str, Icon i, boolean state) – creates a checkbox with string str
and an icon i. If state is true, the check box is initially checked; otherwise it is
cleared.
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.
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:
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");
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);
fileMenu.add(saveItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
frame.setJMenuBar(menuBar);
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:
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)
…………………….
The figure above shows how the model, view, and controller work together to create
a scrollbar component. The scrollbar uses the information in the model to determine how
far into the scrollbar to render the thumb and how wide the thumb should be. Note that
the model specifies this information relative to the minimum and the maximum. It does
not give the position or width of the thumb in screen pixels – the view calculates that.
The view determines exactly where and how to draw the scrollbar, given the proportions
offered by the model. The view knows whether it is a horizontal or vertical scrollbar, and
it knows exactly how to shadow the end buttons and the thumb. Finally, the controller is
responsible for handling mouse events on the component. The controller knows, for
example, that dragging the thumb is a legitimate action for a scroll bar, and pushing on
the end buttons is acceptable as well. The result is a fully functional MVC scrollbar.
Exercises
1. What are the benefits of GUI programming? Compare AWT with Swing.
2. How can you draw two dimensional geometric objects in Java? Explain with suitable
example.
3. Write a Java program using Graphic class to draw different two-dimensional shapes.
4. Write a Java program using Graphic2D class to draw different two-dimensional
shapes.
5. What is event handling? why event handling is important in GUI programming?
6. How can you handle events in Java? Explain.
7. Compare event listener interface with adapter class.
8. What is layout management? Why is the role of layout management? Explain
different layout management classes. How can you use no layout management?
9. Explain some common swing components with example.
10. What is MVC design pattern? Is there any relationship between MVC design pattern
and swing components?
11. 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 sum button and difference if subtract button is clicked.
12. Write a GUI application to calculate simple interest. Use text fields for inputs and
output. Use mouseClick method to generate the result.
13. 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.
14. Try to use adapter classes to handle events in Q.N. 12.