Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Unit 1 - GUI Programming

Ccvv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Unit 1 - GUI Programming

Ccvv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

GUI Programming Unit 1

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.”

Nawaraj Paudel Page 1


GUI Programming Unit 1

Furthermore, Sun developed a platform-independent look-and-feel that was called


“Metal” until the marketing folks renamed it into “Java look-and-feel.” However, most
programmers continue to use the term “Metal”. Some people criticized Metal for being
stodgy, and the look was freshened up for the Java SE 5.0 release. Now the Metal look
supports multiple themes – minor variations in colors and fonts. The default theme is
called “Ocean.”
A new look-and-feel, called Nimbus, is offered since Java SE 7, but it is not available by
default. Nimbus uses vector drawings, not bitmaps, and is therefore independent of the
screen resolution.

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

Nawaraj Paudel Page 2


GUI Programming 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.

Some common methods from java.awt.Component


• boolean isVisible(), void setVisible(boolean b) – gets or sets the visible property.
Components are initially visible, with the exception of top-level components such
as JFrame.
• void setSize(int width, int height) – resizes the component to the specified width
and height.
• void setLocation(int x, int y) – moves the component to a new location. The x and
y coordinates use the coordinates of the container if the component is not a top-
level component, or the coordinates of the screen if the component is top level
(for example, a JFrame).
• void setBounds(int x, int y, int width, int height) – moves and resizes this
component.

Nawaraj Paudel Page 3


GUI Programming Unit 1

• 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

Displaying Information in the Component


Here, we show how to display information (for example button, text field etc.) inside a
frame. One approach to display such information is to use JPanel. The JPanel is a
simplest container class. It provides space in which an application can attach any other
component. It inherits the JComponents class. For example,
import javax.swing.*;
import java.awt.*;
public class SimpleFrame
{
public static void main(String[] args)
{
EventQueue.invokeLater(()->
{
JFrame f = new JFrame();

Nawaraj Paudel Page 4


GUI Programming Unit 1

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);
}
}

Fig: Inheritance hierarchy of JPanel

Working with 2D Shapes


Starting with Java 1.0, the Graphics class from java.awt package has methods to draw
strings, lines, rectangles, ellipses, and so on. For example to draw line, we use
drawLine(x1, y1, x2, y2) method as show below,
class SimplePanel extends JPanel
{
public void paintComponent(Graphics g)
{
g.drawLine(10,10,100,100);
}

Nawaraj Paudel Page 5


GUI Programming Unit 1

}
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.

Nawaraj Paudel Page 6


GUI Programming Unit 1

Fig: 2D rectangle classless

When we construct a Rectangle2D.Float object, we supply the coordinates as float


numbers. For a Rectangle2D.Double object, we supply them as double numbers. For
example,
Rectangle2D.Float floatRect = new Rectangle2D.Float (10.0F, 25.0F, 22.5F, 20.0F);
Rectangle2D.Double doubleRect = new Rectangle2D.Double (10.0, 25.0, 22.5, 20.0);
We can also simply use Rectangle2D variables to hold the rectangle references.
Rectangle2D floatRect = new Rectangle2D.Float (10.0F, 25.0F, 22.5F, 20.0F);
Rectangle2D doubleRect = new Rectangle2D.Double (10.0, 25.0, 22.5, 20.0);
We can also draw rectangles providing two diagonal corner points of a rectangle as
follows:
Rectangle2D rect = new Rectangle2D.Double();
rect.setFrameFromDiagonal(px, py, qx, qy);
Or, even better, if you know the corner points as Point2D objects p and q,
rect.setFrameFromDiagonal(p, q);

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);

Nawaraj Paudel Page 7


GUI Programming Unit 1

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);

Following figures describe the arc types

Nawaraj Paudel Page 8


GUI Programming Unit 1

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);

Nawaraj Paudel Page 9


GUI Programming Unit 1

Drawing General Paths


You can build arbitrary sequences of line segments, quadratic curves, and cubic curves,
and store them in a GeneralPath object. You specify the first coordinate of the path with
the moveTo method. For example,
GeneralPath path = new GeneralPath();
path.moveTo(startX, startY);
Then, you extend the path by calling one of the methods lineTo, quadTo, or curveTo.
These methods extend the path by a line, a quadratic curve, or a cubic curve. To call
lineTo, supply the end point. For the two curve methods, supply the control points, then
the end point. For example,
path.lineTo(endX, endY);
path.quadTo(control1X, control1Y, endX, endY);
path.curveTo(control1X, control1Y, control2X, control2Y, endX, endY)
You can close the path by calling the closePath method. It draws a line back to the last
moveTo. For example,
path.closePath();
To make a polygon, simply call moveTo to go to the first corner point, followed by
repeated calls to lineTo to visit the other corner points. Finally, call closePath to close the
polygon.
A general path does not have to be connected. You can call moveTo at any time to start a
new path segment. For example,
GeneralPath path = new GeneralPath();
path.moveTo(10, 20);
path.lineTo(50,10);
path.moveTo(200, 20);
path.lineTo(50,100);
Finally, you can use the append method to add arbitrary Shape objects to a general path.
The second parameter of the append method is true if the new shape should be connected
to the last points on the path, false if it should not be connected. For example,
GeneralPath path = new GeneralPath();
Rectangle2D floatRect = new Rectangle2D.Float (10.0F, 25.0F, 22.5F, 20.0F);
path.moveTo(10, 20);
path.lineTo(50,10);
path.lineTo(100,10);
path.append(floatRect,true);

Setting Drawing Colors


The setPaint method of the Graphics2D class lets us select a color that is used
for all subsequent drawing operations on the graphics context or component. To draw in
multiple colors, we select a color, draw, then select another color, and draw again.

Nawaraj Paudel Page 10


GUI Programming Unit 1

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);

Text and Fonts


We specify a font by its font face name (or font name for short). A font face name is
composed of a font family name, such as “Helvetica,” and an optional suffix such as
“Bold.” For example, the font faces “Helvetica” and “Helvetica Bold” are both
considered to be part of the family named “Helvetica.” To find out which fonts are
available on a particular computer, call the getAvailableFontFamilyNames
method of the GraphicsEnvironment class. The method returns an array of strings
that contains the names of all available fonts. To obtain an instance of the
GraphicsEnvironment class that describes the graphics environment of the user's
system, use the static getLocalGraphicsEnvironment method. Thus, the
following program gives you a printout of the names of all fonts on your system:

Nawaraj Paudel Page 11


GUI Programming Unit 1

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.

Nawaraj Paudel Page 12


GUI Programming Unit 1

• boolean drawImage(Image img, int x, int y, ImageObserver observer) - draws


an unscaled image.
Here, img is the image to be drawn, x is the x coordinate of the top left corner, y is
the y coordinate of the top left corner, and observer is the object to notify of the
progress of the rendering process (may be null)
• boolean drawImage(Image img, int x, int y, int width, int height,
ImageObserver observer) – draws a scaled image. The system scales the image
to fit into a region with the given width and height.
Here, img is the image to be drawn, x is the x coordinate of the top left corner, y is
the y coordinate of the top left corner, width is the desired width of image, height
is the desired height of image, and observer is the object to notify of the progress
of the rendering process (may be null). For example,
class SimplePanel extends JPanel
{
public void paintComponent(Graphics g)
{
Image i = new ImageIcon("src\\simpleframe\\comp.gif","").getImage();
g.drawImage(i, 10, 10,150,150, null);
}
}

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:

Nawaraj Paudel Page 13


GUI Programming Unit 1

• 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;
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)

Nawaraj Paudel Page 14


GUI Programming Unit 1

{
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

Nawaraj Paudel Page 15


GUI Programming Unit 1

• 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!");
}
}
}

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

Nawaraj Paudel Page 16


GUI Programming Unit 1

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.

Nawaraj Paudel Page 17


GUI Programming Unit 1

Fig: Border layout


The different constructors defined by BorderLayout are as given below:
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,
BorderLayout.EAST, BorderLayout.NORTH, BorderLayout.SOUTH, and
BorderLayout.WEST.
When adding components, we will use these constants with the following form of add().
void add(Component compObj, Object region)
For example,
add(component,BorderLayout.SOUTH);
The border layout grows all components to fill the available space. To solve this problem,
use additional panel. For example,

class SimplePanel extends JPanel


{
private final JButton b1,b2;
private final JTextField t;
public SimplePanel()
{
b1 = new JButton("Ok");
b2 = new JButton("Cancel");
t = new JTextField(8);
setLayout(new BorderLayout());
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
p1.add(b1);
p1.add(b2);
p2.add(t);
add(BorderLayout.NORTH,p1);
add(BorderLayout.SOUTH,p2);
}
}

BoxLayout

Nawaraj Paudel Page 18


GUI Programming Unit 1

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;

Nawaraj Paudel Page 19


GUI Programming Unit 1

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

Nawaraj Paudel Page 20


GUI Programming Unit 1

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))

Nawaraj Paudel Page 21


GUI Programming Unit 1

.addContainerGap(266, Short.MAX_VALUE))
);
}
}

Using No Layout Manager


We can drop a component at a fixed location (absolute positioning) without using any
layout manager. To place a component at a fixed location, we follow the following steps:
• Set the layout manager to null.
• Add the component you want to the container.
• Specify the position and size that you want using setBounds method. The syntax
setBounds method is void setBounds(int x, int y, int width, int height). This
method moves and resizes a component. Parameters x and y are top left corner of
the component and width and height determine new size of the component.
For example,
class SimplePanel extends JPanel
{
private final JButton b1;
private final JTextField t1;
public SimplePanel()
{
b1 = new JButton("Ok");
t1 = new JTextField(8);
setLayout(null);
b1.setBounds(10,10,50,35);
t1.setBounds(70,20,50,35);
add(b1);
add(t1);
}
}
Note: If you want to design your own LayoutManager class that manages components in
a special way you can implement the LayoutManager interface and override the different
methods available.

Common Swing Components


Here, we will discuss most common user interface components in Swing, such as text
fields, radio buttons, and menus that we need most frequently.

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.

Nawaraj Paudel Page 22


GUI Programming Unit 1

• 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

Nawaraj Paudel Page 23


GUI Programming Unit 1

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.

Nawaraj Paudel Page 24


GUI Programming Unit 1

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.

Nawaraj Paudel Page 25


GUI Programming Unit 1

• 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() – 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 s, 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.
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);

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:

Nawaraj Paudel Page 26


GUI Programming Unit 1

• 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");
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

Nawaraj Paudel Page 27


GUI Programming Unit 1

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)
…………………….

Nawaraj Paudel Page 28


GUI Programming Unit 1

Swing and MVC Design Pattern


Swing uses the model-view-controller architecture (MVC) as the fundamental design
behind each of its components. Essentially, MVC breaks GUI components into three
elements. Each of these elements plays a crucial role in how the component behaves.
Model
The model encompasses the state data for each component. There are different models for
different types of components. For example, the model of a scrollbar component might
contain information about the current position of its adjustable “thumb,” its minimum and
maximum values, and the thumb’s width (relative to the range of values). A menu, on the
other hand, may simply contain a list of the menu items the user can select from. Note
that this information remains the same no matter how the component is painted on the
screen; model data always exists independent of the component’s visual representation.
View
The view refers to how you see the component on the screen. For a good example of how
views can differ, look at an application window on two different GUI platforms. Almost
all window frames will have a title bar spanning the top of the window. However, the title
bar may have a close box on the left side (like the older MacOS platform), or it may have
the close box on the right side (as in the Windows platform). These are examples of
different types of views for the same window object.
Controller
The controller is the portion of the user interface that dictates how the component
interacts with events. Events come in many forms - a mouse click, gaining or losing
focus, a keyboard event that triggers a specific menu command, or even a directive to
repaint part of the screen. The controller decides how each component will react to the
event – if it reacts at all.

Fig: Three elements of a model-view-controller architecture

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.

Nawaraj Paudel Page 29


GUI Programming Unit 1

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.

Nawaraj Paudel Page 30

You might also like