[go: up one dir, main page]

0% found this document useful (0 votes)
12 views108 pages

6 GUI - The Model of Design

Uploaded by

sftamman1029
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views108 pages

6 GUI - The Model of Design

Uploaded by

sftamman1029
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

Java Application Design

GUI
Weng Kai
A Little Story
AWT and Swing

3
2014 came the latest version of a new technology known as JavaFX, together with
the announcement that Swing will not be developed further (although it will con-
tinue to be packaged with Java).

Java FX
In Fig. 10.1 you can see some examples of common graphics components using
the three different technologies.

(a) JavaFX (b) Swing (c) AWT (Windows)


Fig. 10.1 Some typical JavaFX components compared with equivalent Swing and AWT
With
components
the release of Java 8 in 2014 came the latest version of
a new technology known as JavaFX.

• And from Java 11, JavaFX has been removed from JDK…..
About the JFC and Swing

• JFC is short for Java Foundation Classes, which


encompass a group of features for building
graphical user interfaces (GUIs) and adding rich
graphics functionality and interactivity to Java
applications.

5
Features of the Java
Foundation Classes
• Swing GUI Components
• Pluggable Look-and-Feel Support
• Accessibility API
• Java 2D API
• Internationalization

6
Swing Features
GUI Principles
• Components: GUI building blocks.
• Buttons, menus, sliders, etc.
• Layout: arranging components to form a usable
GUI.

• Using layout managers.


• Events: reacting to user input.
• Button presses, menu selections, etc.
8
12.3 The Java GUI API 407

Dimension LayoutManager Classes in the java.awt


package
1 Heavyweight
Font

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

Swing GUI
JComponent components such as
JButton, JLabel,
Swing Components
JTextField, JPanel,
in the javax.swing
etc.
Lightweight package

FIGURE 12.1 Java GUI programming utilizes the classes shown in this hierarchical diagram.

instance of JComponent. However, you can use the constructors of concrete subclasses of
JComponent to create JComponent instances. It is important to become familiar with the
of GUI components, such as graphics con
Dialog are the container classes for AWT
Table components. To work with S
12.2.
Container, JFrame, JDialog, JApplet, and JPanel, as described i

Classes TABLE 12.2 GUI Helper Classes


Helper Class Description
TABLE 12.1 GUI Container Classes
java.awt.Graphics is an abstract
Container Class Description lines, and sim

java.awt.Container group components. Frames,deals


is used tojava.awt.Color withand
panels, the
ify backgroun
javax.swing.JFrame is a window not contained inside another window
JPanel , or y
drawings.
user-interface components in Java GUI applicatio
javax.swing.JPanel java.awt.Font
is an invisible specifies font
container that holds user-interface
For example,
inside a container that includes a panel. JPanel i
(e.g., bold), a
javax.swing.JApplet is a subclass of Applet. You must extend
java.awt.FontMetrics JAppl
is an abstract
javax.swing.JDialog is a popup window or message box generally
java.awt.Dimension use
encapsulates
precision)
tion from the user or to provide notification thatin a
java.awt.LayoutManager specifies how

Note
JFrame

• A Frame is a top-level window with a title and a


border.

• A frame, implemented as an instance of the


JFrame class, is a window that typically has
decorations such as a border, a title, and buttons
for closing and iconifying the window.
Applications with a GUI typically use at least one
frame.

11
Creating a frame
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ImageViewer


{
private JFrame frame;

/**

* Create an ImageViewer show it on screen.

*/

public ImageViewer()

makeFrame();

// rest of class omitted.


}

12
code for JFrame

JFrame frame = new ScoreBoard();


frame.pack();
frame.setVisible(true);

13
Elements of a frame
Title Window controls

Menu bar

Content pane

14
JFrame
javax.swing.JFrame

+JFrame() Creates a defaul


+JFrame(title: String) Creates a frame
+setSize(width: int, height: int): void Sets the size of t
+setLocation(x: int, y: int): void Sets the upper-le
+setVisible(visible: boolean): void Sets true to disp
+setDefaultCloseOperation(mode: int): void Specifies the ope
+setLocationRelativeTo(c: Component): Sets the location
void If the compon
+pack(): void Automatically se
frame.

• JFrame
F is a top-level
12.2
IGURE JFrame is acontainer to holdto GUI
top-level container hold GUI components.
components.
The frame is not displayed until the frame.setVisible(true) m
MyFrame.java
frame.setSize(400, 300) specifies that the frame is 400 pixels w
Graphics
Directly Render
1 import javax.swing.*;
2 import java.awt.Graphics;
3
4 public class TestPaintComponent extends JFrame {
5 public TestPaintComponent() {
6 add(new NewPanel() );
7 }
8
9 public static void main(String[] args) {
10 TestPaintComponent frame = new TestPaintComponent();
11 frame.setTitle("TestPaintComponent");
12 frame.setSize(200, 100);
13 frame.setLocationRelativeTo(null); // Center the frame
14 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15 frame.setVisible(true);
16 } (0, 0)
17 }
18 (0, 40) This is a JPanel
19 (50,
class NewPanel 50)
extends JPanel { object placed
inside a frame
20 protected void paintComponent(Graphics g) {
21 super.paintComponent(g);
22 g.drawLine(0, 0, 50, 50);
23 g.drawString("Banner", 0, 40);
24 }
25 } TestPaintComponent.java
java.awt.Graphics

The Graphics
+setColor(color: Color): void Sets
+setFont(font: Font): void Sets a
+drawString(s: String, x: int, y: int): void Draw
+drawLine(x1: int, y1: int, x2: int, y2: Draw
int): void
+drawRect(x: int, y: int, w: int, h: int): Draw
void (
+fillRect(x: int, y: int, w: int, h: int): void Draw
a
+drawRoundRect(x: int, y: int, w: int, h: int, aw: Draw
int, ah: int): void a
+fillRoundRect(x: int, y: int, w: int, h: int, Draw
aw: int, ah: int): void w
+draw3DRect(x: int, y: int, w: int, h: int, Draw

• The Graphics class


raised: boolean): void t
+fill3DRect(x: int, y: int, w: int, h: int, Draw
raised: boolean): void i
contains the methods for +drawOval(x: int, y: int, w: int, h: int):
void
Draw
p

drawing strings and +fillOval(x: int, y: int, w: int, h: int): void Draw
p

shapes. +drawArc(x: int, y: int, w: int, h: int,


startAngle: int, arcAngle: int): void
Draw
r
+fillArc(x: int, y: int, w: int, h: int, Draw
startAngle: int, arcAngle: int): void r
+drawPolygon(xPoints: int[], yPoints: Draw
int[], nPoints: int): void y-
+fillPolygon(xPoints: int[], yPoints: int[], Draw
nPoints: int): void y-
+drawPolygon(g: Polygon): void Draw
+fillPolygon(g: Polygon): void Draw
+drawPolyline(xPoints: int[], yPoints: Draw
int[], nPoints: int): void E
JComponent.

15.4 Drawing Strings, Lines, Rectangles, and Ovals


String and Line
The drawString(String s, int x, int y) method draws a string starting at the point
(x, y), as shown in Figure 15.6(a).
The drawLine(int x1, int y1, int x2, int y2) method draws a straight line from
point (x1, y1) to point (x2, y2), as shown in Figure 15.6(b).
drawString

drawLine

(0, 0) (getWidth(), 0) (0, 0) (getWidth(), 0)

(x1, y1)

(x, y) s is displayed here


(x2, y2)

(0, getHeight()) (getWidth(), getHeight()) (0, getHeight()) (getWidth(), getHeight())


(a) drawString (b) drawLine

FIGURE 15.6 (a) The drawString(s, x, y) method draws a string starting at (x, y). (b) The drawLine(x1, y1,
x2, y2) method draws a line between two specified points.

Java provides six methods for drawing rectangles in outline or filled with color. You can

• drawString(s, x, y)
draw or fill plain rectangles, round-cornered rectangles, or three-dimensional rectangles.
The drawRect(int x, int y, int w, int h) method draws a plain rectangle, and the
fillRect(int x, int y, int w, int h) method draws a filled rectangle. The parameters
drawRect

• drawLine(x1, y1, x2, y2)


fillRect
x and y represent the upper-left corner of the rectangle, and w and h are its width and height
(see Figure 15.7).

(x, y) (x, y)
Color

• public Color(int r, int g, int b);


• setColor(Color color);
• JButton jbtOK = new JButton("OK");
jbtOK.setBackground(color);
jbtOK.setForeground(new Color(100, 1, 1));

• jbtOK.setForeground(Color.RED);
a provides six methods for drawing rectangles in outline or filled with color. You can
r fill plain rectangles, round-cornered rectangles, or three-dimensional rectangles.
drawRect(int x, int y, int w, int h) method draws a plain rectangle, and the

Draw and Fill Rectangle


drawRect
ect(int x, int y, int w, int h) method draws a filled rectangle. The parameters fillRect
y represent the upper-left corner of the rectangle, and w and h are its width and height
gure 15.7).

(x, y) (x, y)

h h

w w

(a) Plain rectangle (b) Filled rectangle

15.7 (a) The drawRect(x, y, w, h) method draws a rectangle. (b) The fillRect(x, y, w, h) method

• drawRect(x, y, w, h)
a filled rectangle.

drawRoundRect(int x, int y, int w, int h, int aw, int ah) method draws a
• fillRect(x, y, w, h)
drawRoundRect
cornered rectangle, and the fillRoundRect(int x, int y, int w, int h, int aw, fillRoundRect
h) method draws a filled round-cornered rectangle. Parameters x, y, w, and h are the
s in the drawRect method, parameter aw is the horizontal diameter of the arcs at the
nd ah is the vertical diameter of the arcs at the corner (see Figure 15.8(a)). In oth
w and ah are the width and the height of the oval that produces a quarter-circle
ner. RoundRect and Oval
aw/2
(x, y) (x, y)
ah/2

h h

w w
(a) drawRoundRect (b) drawOval


5.8 (a) The drawRoundRect(x, y, w, h, aw, ah) method draws a round-
drawRoundRect(x, y, w, h, aw, ah)
rectangle. (b) The drawOval(x, y, w, h) method draws an oval based on its

g rectangle. drawOval(x, y, w, h)
FigurePanel.java
TestFigurePanel.java
raw3DRect(int x, int y, int w, int h, boolean raised) method draws
ngle and the fill3DRect(int x, int y, int w, int h, boolean raised
he easterly direction, and positive angles indicate counterclockwise
ly direction); see Figure 15.11.
is an example of how to draw arcs; the output is shown in Figure 15.
Arcs
(x, y) w

arcAngle

startAngle
h

The drawArc method draws an arc based on an oval with specified a


• drawArc(int x, int y, int w, int h, int startAngle, int arcAngle);

• fillArc(int x, int y, int w, int h, int startAngle, int arcAngle);


.4 DrawArcs.java
DrawArcs.java
int x[] = {40, 70, 60, 45, 20};
int y[] = {20, 40, 80, 45, 60};
g.drawPolygon(x, y, x.length);

The drawing method opens the polygon by drawing lines between point (x[i], y[i]) and

Polygon and Polyline


point (x[i+1], y[i+1]) for i = 0, ... , x.length-1; it closes the polygon by drawing
a line between the first and last points (see Figure 15.15(a)).

(x[0], y[0])
(x[0], y[0])
(x[1], y[1]) (x[1], y[1])
(x[3], y[3]) (x[3], y[3])

(x[4], y[4]) (x[4], y[4])

(x[2], y[2]) (x[2], y[2])

(a) Polygon (b) Polyline

FIGURE 15.15 The drawPolygon method draws a polygon, and the polyLine method draws a polyline.

• Polygon polygon = new Polygon();


polygon.addPoint(40, 20);

• drawPolygon(Polygon polygon);
fillPolygon(Polygon polygon);
Another way polygon

int x[] = {40, 70, 60, 45, 20};


int y[] = {20, 40, 80, 45, 60};
g.drawPolygon(x, y, x.length);
g.drawPolyline(x, y, x.length);

DrawPolygon.java
( se r i f) , ⼀
线
英⽂字 体 从 单 字 上 分 两



Font

2

6



字 ⺟

⽐ 较 上 ⼜ 分 两
线 ( s a n s e r i f) ) 。 衬
种 ⽆ 衬 ( m o n o sp a c e
度 , ⼀ 种 等 宽
⼀ 种 ⾃ 然 宽 , ⽆ 衬 线 字
种, 且 ⾸ 尾 带 装 饰 线
线字 •
public
体 笔 画 有 粗 细
Font(String 变 化,name,
, 也 没
int

style,
装 饰 线
int

size);
⾃ 然 宽 度 字
匀 ⽆ 变 化

画 粗 细 均
体笔 You can choose a font
最 窄 ,等 宽 字
name
体 2 6 from
个 字 ⺟ 全 部
SansSerif, ⼀ 样Serif,
最 宽,
体 mMonospaced,i Dialog, or DialogInput,


宽。choose a style from Font.PLAIN (0), Font.BOLD
(1), Font.ITALIC (2), and Font.BOLD +
Font.ITALIC (3),

• and specify a font size of any positive integer.


• Font font1 = new Font("SansSerif", Font.BOLD,
16);
Font font2 = new Font("Serif", Font.BOLD +
Font.ITALIC, 12);

• JButton jbtOK = new JButton("OK");


jbtOK.setFont(font1);
Enum Fonts

GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
for (int i = 0; i < fontnames.length; i++)
System.out.println(fontnames[i]);
descending characters (e.g., j, y, and g) in the font will be above the desce
some may extend below the descent line.

FontMetrics
Height is the sum of leading, ascent, and descent.

Leading

By
Ascent line

Height Ascent

Baseline
Descent
Descent line

5.17 The FontMetrics class can be used to determine the font propert
• In Graphics:
rs for a given font.
• FontMetrics getFontMetrics(Font font)
trics is an abstract class. To get a FontMetrics object for a specific fo
• FontMetrics getFontMetrics()
g getFontMetrics methods defined in the Graphics class:
TestCenterMessage.java
FontMetrics
This is a MessagePanel object

• public int getAscent() // Return the ascent


• public int getDescent() // Return the descent
stringWidth()

• public int getLeading() // Return the leading


getHeight()
stringAscent()

• public int getHeight() // Return the height


• public int stringWidth(String str) // Return the
(xCoordinate, yCoordinate)
width of the string xCoordinate = getWidth / 2 - stringWidth / 2;
yCoordinate = getHeight / 2 - stringAscent / 2;

MessagePanel.java
TestMessagePanel.java
Images as Icons

• ImageIcon icon = new ImageIcon("image/us.gif");


JLabel jlblImage = new JLabel(imageIcon);

• Image image = imageIcon.getImage();


• g.drawImage(image, 0, 0, getWidth(), getHeight(),
this);
much control over how the image is displayed. A more flexible way to dis
use the drawImage method of the Graphics class on a panel. Four
drawImage method are shown in Figure 15.23.

java.awt.Graphics
+drawImage(image: Image, x: int, y: int, Draws the image in a sp
bgcolor: Color, observer: (x, y) in the graphics c
ImageObserver): void the image are drawn i
object on which the im
larger than the area it
+drawImage(image: Image, x: int, y: int, Same as the preceding m
observer: ImageObserver): void color.
+drawImage(image: Image, x: int, y: int, Draws a scaled version
width: int, height: int, observer: in the specified rectan
ImageObserver): void
+drawImage(image: Image, x: int, y: int, Same as the preceding m
width: int, height: int, bgcolor: Color, color behind the imag
observer: ImageObserver): void

FIGURE 15.23 You can apply the drawImage method on a Graphics obje
• JPanel is a kind of ImageObserver
ImageObserver specifies a GUI component for receiving notifications o
DisplayImage.java
tion as the image is constructed. To draw images using the drawImage m
component, such as JPanel, override the paintComponent method to te
LayoutManager
The content pane
/**

* Create the Swing frame and its content.

*/

private void makeFrame()

frame = new JFrame("ImageViewer");

a tio n .
Container contentPane = frame.getContentPane();
deleg
t-pa n e
con ten
JLabel label = new JLabel("I am a label.");

contentPane.add(label);

frame.pack();

frame.setVisible(true);

34
12.4.2 Adding Components to a Frame
frame.add(jbtOK);
The frame shown in Figure 12.3(a) is empty. Using the add method, you can add comp

Adding Components
into the frame, as in Listing 12.2.
e delegation This new feature is called content-pan
LISTING 12.2 MyFrameWithComponents.java
into the MyFrameWithComponents.java
1 import javax.swing.*;
content pane of a frame. Fo
2
frame.
3 public class MyFrameWithComponents {
4
5
An object of JButton was created
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrameWithComponents");
6
7
to the content pane of the frame (line 9
// Add a button into the frame
8
9 frame.add(jbtOK);
The add(Component comp) meth
JButton jbtOK = new JButton("OK");

10 Component to the container. Since J


11 frame.setSize(400, 300);
w 12 JButton is also an instance of Compon
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13 frame.setLocationRelativeTo(null); // Center the frame
14 remove method. The following statem
frame.setVisible(true);
15 }
16 }
container.remove(jbtOK);
Each JFrame contains a content pane. A content pane is an instance of java.awt.Cont
The GUI components such as buttons are placed in the content pane in a frame. In earlier
Layout Manager

• The layout manager works behind the scenes to


place components in the correct locations.
LayoutManager layoutManager = new XLayout();
container.setLayout(layoutManager);
FlowLayout
• The components are arranged in the container
from left to right in the order in which they were
added. When one row is filled, a new row is
started.

• You can specify the way the components are


aligned by using one of three constants: FlowLay-
out.RIGHT, FlowLayout.CENTER, or
FlowLayout.LEFT.You can also specify the gap
between components in pixels.
12.5.1 FlowLayout

FlowLayout
FlowLayout is the simplest layout manager. The components are arranged in the container from
left to right in the order in which they were added. When one row is filled, a new row is started.
Video No
You can specify the way the components are aligned by using one of three constants: FlowLay- Use Flow
out.RIGHT, FlowLayout.CENTER, or FlowLayout.LEFT. You can also specify the gap
between components in pixels. The class diagram for FlowLayout is shown in Figure 12.4.

The get and set methods for these data


fields are provided in the class, but
omitted in the UML diagram for brevity.
java.awt.FlowLayout

-alignment: int The alignment of this layout manager (default: CENTER).


-hgap: int The horizontal gap of this layout manager (default: 5 pixels).
-vgap: int The vertical gap of this layout manager (default: 5 pixels).

+FlowLayout() Creates a default FlowLayout manager.


+FlowLayout(alignment: int) Creates a FlowLayout manager with a specified alignment.
+FlowLayout(alignment: int, hgap: Creates a FlowLayout manager with a specified alignment,
int, vgap: int) horizontal gap, and vertical gap.

FIGURE 12.4 FlowLayout lays out components row by row.


ShowFlowLayout.java
Listing 12.3 gives a program that demonstrates flow layout. The program adds three labels
and text fields into the frame with a FlowLayout manager, as shown in Figure 12.5.
The GridLayout manager arranges components in a grid (matrix) formation. The compo-
nents are placed in the grid from left to right, starting with the first row, then the second, and
so on, in the order in which they are added. The class diagram for GridLayout is shown in
Figure 12.6.
GridLayout
The get and set methods for these data
fields are provided in the class, but
omitted in the UML diagram for brevity.
java.awt.GridLayout

-rows: int The number of rows in this layout manager (default: 1).
-columns: int The number of columns in this layout manager (default: 1).
-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).

+GridLayout() Creates a default GridLayout manager.


+GridLayout(rows: int, columns: int) Creates a GridLayout with a specified number of rows and columns.
+GridLayout(rows: int, columns: int, Creates a GridLayout manager with a specified number of rows and
hgap: int, vgap: int) columns, horizontal gap, and vertical gap.

FIGURE 12.6 GridLayout lays out components in equal-sized cells on a grid.

• The components are placed in the grid from left to right,


starting with the first row, then the second, and so on, in the
order in which they are added.
ShowGridLayout.java
it yourself.

BorderLayout
Note add(Component, index)
In FlowLayout and GridLayout, the order in which the components are added to the con-
BorderLayout.EAST,
tainer is important. It determines the location of the components in the container.

.5.3 BorderLayout BorderLayout.SOUTH,


e BorderLayout manager divides a container into fiveBorderLayout.WEST,
areas: East, South, West, North,
Center. Components are added to a BorderLayout by using add(Component,
dex), where index is a constant BorderLayout.EAST BorderLayout.NORTH,
, BorderLayout.SOUTH,
BorderLayout.CENTER
rderLayout.WEST, BorderLayout.NORTH, or BorderLayout.CENTER. The class dia-
m for BorderLayout is shown in Figure 12.8.

The get and set methods for these data


ut divides the container into five areas, each of which can hold a
fields are provided in the class, but
omitted in the UML diagram for brevity.
java.awt.BorderLayout

-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).
frame (lines 11–15). Note that the add method for BorderLayout
+BorderLayout() Creates a default BorderLayout manager.
FlowLayout and GridLayout
+BorderLayout(hgap: int, vgap: int). With BorderLayout
Creates a BorderLayout manager youwith specify
a specified number of
horizontal gap, and vertical gap.
.
components
URE to occupy
12.8 BorderLayout all the areas.
lays out components If you remove
in five areas. the East but-
ShowBorderLayout.java
erun it, you will see that the center stretches rightward to occupy
Properties of Layout
Managers
// Create a layout manager
FlowLayout flowLayout = new FlowLayout();
// Set layout properties
flowLayout.setAlignment(FlowLayout.RIGHT);
flowLayout.setHgap(10); flowLayout.setVgap(20);
frame.setSize(400, 250);
frame.setLocationRelativeTo(null); // Center the frame

}
Using Panels as
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}
Subcontainers
Frame

Content panel
Button
Panel p2

Panel p1

12.10 The program uses panels to organize components.


• Panels can be placed inside a frame or inside
URE

another
setLayout method panel.in java.awt.Container. Since JPanel is a subclass
is defined
tainer, you can use setLayout to set a new layout manager in the panel (line 8). Li
can be replaced by JPanel p1 = new JPanel(new GridLayout(4,TestPanels.java
3)).
To achieve the desired layout, the program uses panel p1 of GridLayout to group
Common
java.awt.Component

-font: java.awt.Font The


-background: java.awt.Color The

Features of
-foreground: java.awt.Color The
-preferredSize: java.awt.Dimension The
-visible: boolean Ind

Swing GUI
+getWidth(): int Ret
+getHeight(): int Ret
+getX(): int get
+getY(): int co

Components java.awt.Container

+add(comp: Component): Component Add


+add(comp: Component, index: int): Component Add
+remove(comp: Component): void Rem
+getLayout(): LayoutManager Ret
+setLayout(l: LayoutManager): void Sets
+paintComponents(g: Graphics): void Pain

javax.swing.JComponent

-toolTipText: String The


t
-border: javax.swing.border.Border The
thickness of the line.
Listing 12.7 is an example to demonstrate Swing common features. The example creates a
panel p1 to hold three buttons (line 8) and a panel p2 to hold two labels (line 25), as shown in

What are they


Figure 12.12. The background of the button jbtLeft is set to white (line 12) and the fore-
ground of the button jbtCenter is set to green (line 13). The tool tip of the button jbtRight
is set in line 14. Titled borders are set on panels p1 and p2 (lines 18, 36) and line borders are
set on the labels (lines 32–33).

Titled border Having the mouse cursor


over the Right button
displays the tool tip text

Titled border
Line border

FIGURE 12.12 The font, color, border, and tool tip text are set in the message panel.

LISTING 12.7 TestSwingCommonFeatures.java


1 import java.awt.*;
2 import javax.swing.*; TestSwingCommonFeatures.java
3 import javax.swing.border.*;
5 Graphics StillClock
(0, 0)

(xEnd, yEnd)

12

! handLength

9 3
(xCenter, yCenter)

(a) (b)

FIGURE 15.22 (a) The DisplayClock program displays a clock that shows the current time.
(b) The endpoint of a clock hand can be determined, given the spanning angle, the hand
length, and the center point.
DisplayClock.java
The position of the minute hand is determined by the minute and second. The exact minute
value combined with seconds is minute + second/60. For example, ifStillClock.java
the time is 3 minutes
and 30 seconds, the total minutes are 3.5. Since there are 60 minutes in one hour, the angle for
the minute hand is
Frame
Elements of a frame
Title Window controls

Menu bar

Content pane

47
Adding menus
•JMenuBar
• Displayed below the title.
• Contains the menus.
•JMenu
• e.g. File. Contains the menu items.
•JMenuItem
• e.g. Open. Individual items.
48
The Menus

49
private void makeMenuBar(JFrame frame)
{
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);

// create the File menu


JMenu fileMenu = new JMenu("File");
menubar.add(fileMenu);

JMenuItem openItem = new JMenuItem("Open");


fileMenu.add(openItem);

JMenuItem quitItem = new JMenuItem("Quit");


fileMenu.add(quitItem);
}

50
To create menus
• Create a JMenuBar, set it to the JFrame
• Create some JMenus, add them to the
JMenuBar
• Create some JMenuItems, add them to the
JMenus
• Add ActionListener to every JMenuItems to
receive the event
Event handling

• Events correspond to user interactions with


components.

• Components are associated with different event


types.
• Frames are associated with WindowEvent.
• Menus are associated with ActionEvent.
• Objects can be notified when an event occurs.
• Such objects are called listeners.
52
Centralized event receipt

• A single object handles all events.


• Implements the ActionListener interface.
• Defines an actionPerformed method.
• It registers as a listener with each component.
–item.addActionListener(this)

• It has to work out which component has


dispatched the event.

53
public class ImageViewer implements ActionListener
{

public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if(command.equals("Open")) {

}
else if (command.equals("Quit")) {

}

}

private void makeMenuBar(Jframe frame)
{

openItem.addActionListener(this);

}
}

54
Centralized event
handling
• The approach works.
• It is used, so you should be aware of it.
• However …
• It does not scale well.
• Identifying components by their text is fragile.
• An alternative approach is preferred.
55
Anonymous action listener
JMenuItem openItem = new JMenuItem("Open");

openItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openFile();
}
});

56
Anonymous action listener
JMenuItem openItem = new JMenuItem("Open");

openItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openFile();
}
});

57
What Events We Have?
• ActionEvent
• MouseEvent
• AdjustmentEvent
• MouseMotion
• ComponentEvent
• WindowEvent
• ContainerEvent
• ItemEvent
• FocusEvent
• TextEvent
• KeyEvent
536 Chapter 16 Event-Driven Programming

Trigger an event «interface»


User source: SourceClass XListener
Action +addXListener(listener: XListener) +handler(event: XEvent)
(2) Register by invoking
source.addXListener(listener);
(1) A listener object is an
instance of a listener interface listener: ListenerClass

(a) A generic source component with a generic listener


«interface»
source: javax.swing.JButton java.awt.event.ActionListener
+addActionListener(listener: ActionListener) +actionPerformed(event: ActionEvent)
(2) Register by invoking
source.addActionListener(listener);

(1) An action event listener is an listener: CustomListenerClass


instance of ActionListener
(b) A JButton source component with an ActionListener

FIGURE 16.3 A listener must be an instance of a listener interface and must be registered with a source component.

1. The listener object must be an instance of the corresponding event-listener interface to


ensure that the listener has the correct method for processing the event. Java provides a
listener interface listener interface for every type of event. The listener interface is usually named
Dynamic Events

• There is more than one listener attached to each


components.

• During the execution of the program, listeners


are dynamically added and removed.

DynamicEvents.java
How Does It Work?
components and dialogs
interfaces.
Many Java IDEs provide tools for visually designing and developing GUI interfaces. This
enables you to rapidly assemble the elements of a user interface (UI) for a Java application or

Components
applet with minimum coding. Tools, however, cannot do everything. You have to modify the
programs they produce. Consequently, before you begin to use the visual tools, you must
understand the basic concepts of Java GUI programming.
Previous chapters briefly introduced several GUI components. This chapter introduces the
frequently used GUI components in detail (see Figure 17.1). (Since this chapter introduces no
new concepts, instructors may assign it for students to study on their own.)

JButton
Component Container JComponent AbstractButton JCheckBox
JToggleButton
JRadioButton
JLabel
JTextArea
JTextComponent
JTextField JPasswordField
JComboBox

JList

JScrollBar

JSlider

FIGURE 17.1 These Swing GUI components are frequently used to create user interfaces.

Note
1

javax.swing.JComponent
JButton The get and set methods for these data fields are
in the class, but omitted in the UML diagram for bre
javax.swing.AbstractButton

-actionCommand: String The action command of this button.


-text: String The button’s text (i.e., the text label on the button).
-icon: javax.swing.Icon The button’s default icon. This icon is also used as the “pre
“disabled” icon if there is no pressed icon set explicitly.
-pressedIcon: javax.swing.Icon The pressed icon (displayed when the button is pressed).
-rolloverIcon: javax.swing.Icon The rollover icon (displayed when the mouse is over the bu
-mnemonic: int The mnemonic key value of this button. You can select the
pressing the ALT key and the mnemonic key at the same
-horizontalAlignment: int The horizontal alignment of the icon and text (default: CE
-horizontalTextPosition: int The horizontal text position relative to the icon (default: R
-verticalAlignment: int The vertical alignment of the icon and text (default: CENT
-verticalTextPosition: int The vertical text position relative to the icon (default: CEN
-borderPainted: boolean Indicates whether the border of the button is painted. By d

-iconTextGap: int
• TestButtonIcons.java
button’s border is painted, but the borders for a check b
button are not painted.
The gap between the text and the icon on the button.
-selected(): boolean • ButtonDemo.java
The state of the button. True if the check box or radio butt
false if not.
JCheckBox inherits all the properties from AbstractButton,
Video Note
Use check boxes mnemonic, verticalAlignment, horizontalAlignment, horiz
verticalTextPosition, and selected, and provides several cons

CheckBoxes
boxes, as shown in Figure 17.11.

javax.swing.AbstractButton

javax.swing.JToggleButton

javax.swing.JCheckBox

+JCheckBox() • CheckBoxDemo.ja
Creates a default check box button with no text a
+JCheckBox(text: String)
+JCheckBox(text: String, selected:
va
Creates a check box with text.
Creates a check box with text and specifies wheth
boolean) initially selected.
+JCheckBox(icon: Icon) Creates a checkbox with an icon.
+JCheckBox(text: String, icon: Icon) Creates a checkbox with text and an icon.
+JCheckBox(text: String, icon: Icon, Creates a check box with text and an icon, and sp
selected: boolean) box is initially selected.
+addActionListener(listener: Adds an ActionListener for this object.
ActionListener) : void
+addItemListener(listener: ItemListener) Adds an ItemListener for this object.
: void
GUI helper class ButtonGroup is not a subclass of java.awt.Component, so a ButtonGroup obje
radio buttons, as shown in Figure 17.13. These constructors are similar to the constructors for
not be added to a container.
JCheckBox. When a radio button is changed (selected or deselected), it fires an ItemEvent
ActionEvent. To see if a radio button is selected, use the isSelected() metho

RadioButton
Listing 17.4 gives a program that adds three radio buttons named Red, Gree
to the preceding example to let the user choose the color of the message, a
Figure 17.14.

javax.swing.AbstractButton
JPanel with
GridLayout
for three
radio buttons
javax.swing.JToggleButton

FIGURE 17.14 Three radio buttons are added to specify the color of the message.
javax.swing.JRadioButton

+JRadioButton() AgainCreates
there areaatdefault
least tworadio button
approaches with no
to writing thistext and The
program. icon.
first is t
preceding CheckBoxDemo class to insert the code for adding the radio buttons and
+JRadioButton(text: String) Creates
their events. The a radiois button
second to createwith text.that extends CheckBoxDemo. L
a subclass
gives the code to implement the second approach.
+JRadioButton(text: String, selected: Creates a radio button with text and specifies whether th
boolean) initially selected.
LISTING 17.4 RadioButtonDemo.java
+JRadioButton(icon: Icon) Creates
1 import a radio button with an icon.
java.awt.*; JF
2 import java.awt.event.*;
+JRadioButton(text: String, icon: Icon) Creates a radio button with text and an icon.
3 import javax.swing.*;

• RadioButtonDemo.java
+JRadioButton(text: String, icon: Icon, 4 Creates a radio button with text and an icon, and specifie
Butt
5 public class RadioButtonDemo extends CheckBoxDemo {
selected: boolean) 6
radio button is initially selected.
// Declare radio buttons
+addActionEvent(listener: 7 Adds an
private ActionListener
JRadioButton for this object.
jrbRed, jrbGreen, jrbBlue; Check
8
ActionListener): void 9 public static void main(String[] args) {
+addItemListener(listener:
create ItemListener)
frame 10 Adds an ItemListener
RadioButtonDemo frame = new forRadioButtonDemo();
this object. RadioB
11 frame.setSize(500, 200);
: void 12 frame.setLocationRelativeTo(null); // Center the frame
13 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
javax.swing.JComponent

The get and set methods for these data fields are provided

Label
in the class, but omitted in the UML diagram for brevity.
javax.swing.JLabel

-text: String The label’s text.


-icon: javax.swing.Icon The label’s image icon.
-horizontalAlignment: int The horizontal alignment of the text and icon on the label.
-horizontalTextPosition: int The horizontal text position relative to the icon on the label.
-verticalAlignment: int The vertical alignment of the text and icon on the label.
-verticalTextPosition: int The vertical text position relative to the icon on the label.
-iconTextGap: int The gap between the text and the icon on the label.
+JLabel() Creates a default label with no text and icon.
+JLabel(icon: javax.swing.Icon) Creates a label with an icon.
+JLabel(icon: Icon, hAlignment: int) Creates a label with an icon and the specified horizontal alignment.
+JLabel(text: String) Creates a label with text.
+JLabel(text: String, icon: Icon, Creates a label with text, an icon, and the specified horizontal alignment.
hAlignment: int)
+JLabel(text: String, hAlignment: int) Creates a label with text and the specified horizontal alignment.

FIGURE 17.15 JLabel displays text or an icon, or both.

// Create an image icon from an image file


ImageIcon icon = new ImageIcon("image/grapes.gif");
17.6 Text Fields
// Create a label with a text, an icon,
A text field can be used to enter or display a string. JTextField is a subclass of
// with JTextComponent
centered horizontal alignment
. Figure 17.16 lists the constructors and methods in JTextField.
Video Note JLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER);
Use labels and text fields
JTextField inherits JTextComponent , which inherits JComponent. Here is an
//Set label's
example text alignment
of creating and gap
a text field with between text color
red foreground and and
iconright horizontal
alignment:
jlbl.setHorizontalTextPosition(SwingConstants.CENTER);
jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);
JTextField jtfMessage = new JTextField("T-Strom");
jlbl.setIconTextGap(5);
jtfMessage.setForeground(Color.RED);
jtfMessage.setHorizontalAlignment(SwingConstants.RIGHT);

When you move the cursor in the text field and press the Enter key, it fires an ActionEvent.
Listing 17.5 gives a program that adds a text field to the preceding example to let the user
+JTextField() Creates a default empty text field with numb
+JTextField(column: int) Creates an empty text field with a specified
+JTextField(text: String) Creates a text field initialized with the speci
+JTextField(text: String, columns: int) Creates a text field initialized with the speci
+addActionEvent(listener: ActionListener): Adds an ActionListener for this object.

TextField
void
17.6 Text Fields 585
FIGURE 17.16 JTextField enables you to enter or display a string.

The get and set methods for these data fields are provided
javax.swing.text.JTextComponent in the class, but omitted in the UML diagram for brevity.
-text: String JPanel with
The text contained in this text component. BorderLayout
-editable: boolean for a label and
Indicates whether this text component is editable (default: true).
a text field

javax.swing.JTextField

-columns: int The number of columns in this text field.


-horizontalAlignment: int The horizontal alignment of this text field (default: LEFT).
+JTextField() FIGURE Creates
17.17 aAdefault empty
label and text field
a text field with number
are added to of
setcolumns set to 0.
a new message.
+JTextField(column: int) Creates an empty text field with a specified number of columns.
+JTextField(text: String) Creates a text field initialized with the specified text.
+JTextField(text: String, columns: int) ISTING L 17.5
Creates a text TextFieldDemo.java
field initialized with the specified text and columns.
+addActionEvent(listener: ActionListener):1 import
Adds an ActionListener for this object.
java.awt.*;
void 2 import java.awt.event.*;
3 import javax.swing.*;
FIGURE 17.16 JTextField enables you to enter 4
or display a string.
5 public class TextFieldDemo extends RadioButtonDemo {
6 private JTextField jtfMessage = new JTextField(10);
7
8 /** Main method */
9 public static voidwith
JPanel main(String[] args) {

• TextFieldDemo.java
10 TextFieldDemo frame = new TextFieldDemo();
BorderLayout c
11 frame.pack();
for a label and p
12 a text field
frame.setTitle("TextFieldDemo");
13 frame.setLocationRelativeTo(null); // Center the frame
14 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15 frame.setVisible(true);
16 }
17
18 public TextFieldDemo() { c
17.7 Text Areas 587

TextArea
Listing 17.7 gives a program that displays an image and a text in a label, and a text in a text
area, as shown in Figure 17.19.

17.7 Text Areas 587


javax.swing.text.JTextComponent
Listing 17.7 gives a program that displays an image and a text in a label, and a text in a text
The get and set methods for these data fields are provided
area, as shown in Figure 17.19.
in the class, but omitted in the UML diagram for brevity.
javax.swing.JTextArea
javax.swing.text.JTextComponent
-columns: int The number
The get and ofset
columns
methods forinthese
thisdata
text area.
fields are provided
in the class, but omitted in the UML diagram for brevity.
-rows: int javax.swing.JTextArea
The number of rows in this text area.
-tabSize: int The number of characters used to expand tabs (default: 8).
-columns: int The number of columns in this text area.
-lineWrap: boolean
-rows: int
Indicates whether the line in the text area is automatically
The number of rows in this text area.
-tabSize: int wrapped
The number (default:
of characters false).
used to expand tabs (default: 8).

• DescriptionPanel.java
-lineWrap: boolean Indicates whether the line in the text area is automatically
-wrapStyleWord: boolean Indicates whether
wrapped (default: false).the line is wrapped on words or characters (default: false).
-wrapStyleWord: boolean Indicates whether the line is wrapped on words or characters (default: false).
+JTextArea() Creates a default empty text area.
+JTextArea() Creates a default empty text area.
+JTextArea(rows: +JTextArea(rows:
int, columns: int,int)
columns: int) Creates an empty
Creates an empty text areatext area
with the withnumber
specified the specified number of rows and columns.
of rows and columns.

• TextAreaDemo.java
+JTextArea(text: +JTextArea(text:
String) String) Creates
Creates a newa new text
text area witharea with text
the specified thedisplayed.
specified text displayed.
+JTextArea(text: String, rows: int, columns: int) Creates a new text area with the specified text and number of rows and columns.
+JTextArea(text: +append(s:
String, String):
rows: void
int, columns: int) Creates a new text area with the specified text and number of rows and columns.
Appends the string to text in the text area.
+append(s: String): void String, pos: int): void
+insert(s: Appends
Inserts string sthe string
in the toposition
specified text in thetext
in the text
area.area.
+replaceRange(s: String, start: int, end: int): Replaces partial text in the range from position start to end with string s.
+insert(s: String,void
pos: int): void Inserts string s in the specified position in the text area.
+replaceRange(s: +getLineCount():
String, start: int int, end: int): Replaces partial
Returns the actual numbertext in the
of lines range
contained from
in the position start to end with string s.
text area.

void
+getLineCount():FIGURE
int 17.18 JTextArea enables you to enter or displayReturns
multiplethe lines of characters.
actual number of lines contained in the text area.

FIGURE 17.18 JTextArea enables you to enter or display multiple lines of characters.
DescriptionPanel
with BorderLayout

A label
showing an A text area
image and a inside a
scroll panel
DescriptionPanel
text
with BorderLayout

FIGURE 17.19 The program displays an image in a label, a title in a label, and a text in the text area.
590 Chapter
getSelectedItem(): Object17 Creating Graphical User
Returns the Interfaces
selected item.
setSelectedItem(item: Object): void Sets the selected item in the combo box.
removeItem(anObject: Object): void 17.8 Combo Boxes
Removes an item from the item list.
removeItemAt(anIndex: int): void A comboRemoves
box, alsothe item as
known at athe specified
choice index
list or in the combo
drop-down box.
list, contains a list of items from

ComboBox
removeAllItems(): void which theRemoves
user canall
choose. It isinuseful
the items in limiting
the combo box. a user’s range of choices and avoids the
addActionEvent(listener: cumbersome
Addsvalidation of data input. Figure
an ActionListener for this17.21 lists several frequently used constructors
object.
ActionListener): void and methods in JComboBox.
addItemListener(listener: Adds an ItemListener for this object.
ItemListener) : void
javax.swing.JComponent

7.21 JComboBox enables you to select an item from a set of items.


javax.swing.JComboBox

The following statements create a combo


+JComboBox() box
Creates withempty
a default fourcombo
items,box.red foreground, white back-
+JComboBox(items: Object[])
ground, and the second item selected. Creates a combo box that contains the elements in the specified array.
+addItem(item: Object): void Adds an item to the combo box.
+getItemAt(index: int): Object Returns the item at the specified index.
JComboBox jcb = new JComboBox(new Object[]
+getItemCount(): int Returns the number of items in the combo box.
{"Item 1", "Item 2", "Item 3", "Item 4"});
+getSelectedIndex(): int Returns the index of the selected item.
jcb.setForeground(Color.red);
+setSelectedIndex(index: int): void Sets the selected index in the combo box.
jcb.setBackground(Color.white);
+getSelectedItem(): Object Returns the selected item.
jcb.setSelectedItem("Item
+setSelectedItem(item: Object): void 2");Sets the selected item in the combo box.
+removeItem(anObject: Object): void Removes an item from the item list.
JComboBox can fire ActionEvent
+removeItemAt(anIndex: int): void and Removes
ItemEvent the item, among manyindex
at the specified other events.
in the Whenever an
combo box.
item is selected, an void
+removeAllItems(): ActionEvent is fired. Whenever
Removes a new
all the items item
in the combois box.
selected, JComboBox fires
+addActionEvent(listener:
ItemEvent Adds
twice, once for deselecting the an ActionListener
previously selectedfor this object.
item, and the other for selecting
ActionListener): void
the currently selected item. Note that no ItemEvent
+addItemListener(listener: is fired if
Adds an ItemListener forthe
this current
object. item is reselected. To
respond to an ItemEvent
ItemListener) : void , you need to implement the itemStateChanged(ItemEvent e)
handler for processing a choice. To get data from a JComboBox menu, you can use
FIGURE 17.21 JComboBox enables you to select an item from a set of items.
getSelectedItem() to return the currently selected item, or e.getItem() method to get the

• ComboBoxDemo.java
item from the itemStateChanged(ItemEvent e) handler.
Listing 17.8 givesThe following statements create a combo box with four items, red foreground, white back-
a program that lets users view an image and a description of a country’s
ground, and the second item selected.
flag by selecting the country from a combo box, as shown in Figure 17.22.
Here are the majorJComboBox
steps in the
jcbprogram:
= new JComboBox(new Object[]
{"Item 1", "Item 2", "Item 3", "Item 4"});
1. Create the userjcb.setForeground(Color.red);
interface.
jcb.setBackground(Color.white);
Create a combo box with country names as its selection values.
jcb.setSelectedItem("Item 2");
Create a Descrip-
tionPanel object. The DescriptionPanel class was introduced in the preceding
JComboBox can fire ActionEvent and ItemEvent, among many other events. Whenever an
itemStateChanged handler is executed, finds the selected index, and sets its corresponding
selectionMode
flag title, flag image, and flag description on the panel. is one of the three values (SINGLE_SELECTION, SINGLE_INTER
_SELECTION, MULTIPLE_INTERVAL_SELECTION) defined in javax.swing.List
17.9 Lists lectionModel that indicate whether a single item, single-interval item, or multiple-inte

List
item
A list is a component that basically can be
performs selected.
the same functionSingle selection
as a combo allows only one item to be selected. Single-inte
box but enables
the user to choose a single value or multiple values. The Swing JList is very versatile.
selection allows multiple selections, but the selected items must be contiguous. Multi
Figure 17.23 lists several frequently used constructors and methods in JList.
interval selection allows selections of multiple contiguous items without restrictions
javax.swing.JComponent shown in Figure 17.24. The default value is MULTIPLE_INTERVAL_SELECTION.
The get and set methods for these data fields are provided
in the class, but omitted in the UML diagram for brevity.
javax.swing.JList

-selectedIndex: int The index of the first selected item.


-selectedIndices: int[] An array of all of the selected indices in increasing order.
-selectedValue: Object The first selected item in the list.
-visibleRowCount: int The number of visible rows displayed without a scrollbar
(default: 8).
-selectionBackground: Color The background color of the selected cells.
-selectionForeground: Color The foreground color of the selected cells.
-selectionMode: int (a) Single
The selection modeselection
for the list. (b) Single-interval (c) Multiple-interval
selection selection
+JList() Creates a default empty list.
+JList(items: Object[]) IGURE F 17.24 has three selection modes: single selection, single-interval selectio
Creates a list that contains the elements in the specified array.
JList
+addListSelectionListener(listener: Adds a ListSelectionListener to this object.
ListSelectionListener): void and multiple-interval selection.
FIGURE 17.23 JList enables you to select multiple items from a set of items.

selectionMode is one of the three values (SINGLE_SELECTION, SINGLE_INTERVAL

• ListDemo.java
_SELECTION, MULTIPLE_INTERVAL_SELECTION) defined in javax.swing.ListSe-
lectionModel that indicate whether a single item, single-interval item, or multiple-interval
item can be selected. Single selection allows only one item to be selected. Single-interval
selection allows multiple selections, but the selected items must be contiguous. Multiple-
interval selection allows selections of multiple contiguous items without restrictions, as
shown in Figure 17.24. The default value is MULTIPLE_INTERVAL_SELECTION.
ted item and sets their corresponding image icons
17.26. in the label to display the flags.
-unitIncrement: int Specifies the value added (subtracted) when the user activates the unit-
increment (decrement) area of the scroll bar, as shown in Figure

10 Scroll Bars 17.26.

ScrollBar
+JScrollBar() Creates a default vertical scroll bar.
rollBar is a component that enables the user to select from a range of values, as shown
+JScrollBar(orientation: int) Creates a scroll bar with the specified orientation.
gure 17.26.
+JScrollBar(orientation: int, value: javax.swing.JComponent
Creates a scroll bar with the specified orientation, value, extent,
int, extent: int, min: int, max: int) minimum, and maximum. The get an
in the class
+addAdjustmentListener(listener: Adds an AdjustmentListener to this object.
AdjustmentListener):
Minimum value void Maximum value javax.swing.JScrollBar
Block decrement Block increment
IGURE 17.27 JScrollBar enables you to select from a range of values. -orientation: int Specifies horizo
-maximum: int Specifies the m
reaches the r
Listing 17.10 gives a program that uses horizontal and vertical scroll bars to control a mes- bottom of th
age displayed on a panel. The horizontal scroll bar is used to move the message to the left or -minimum: int Specifies the m
he right, and the vertical scroll bar to move it up and down. A sample run of the program is
Bubble reaches the l
the scroll bar
hown in Figure 17.28.
Unit decrement Unit increment
-visibleAmount: int Specifies the re
RE 17.26 A scroll bar represents a range of values graphically. appearing on
value of vis
-value: int Represents the
Message panel Vertical scroll bar -blockIncrement: int Specifies value
ormally, the user changes the value of the scroll bar by making a gesture with the mouse. increment (d
example, the user can drag the scroll bar’s bubble up and down, or click in the scroll bar’s
Horizontal scroll bar
17.26.
increment or block-increment areas. Keyboard gestures can also be mapped to the scroll
-unitIncrement: int Specifies the va
increment (d
By convention,
GURE the Page
17.28 The scroll Up and
bars move Page Down
the message keyshorizontally
on a panel are equivalent to clicking in the scroll
and vertically.
17.26.
block-increment and block-decrement areas.
Here are the major steps in the program: +JScrollBar() Creates a defau
+JScrollBar(orientation: int) Creates a scroll
Note
1. Create the user interface.
TheCreate
width aofMessagePanel
the scroll bar’s track
objectcorresponds
and place ittoinmaximum When a+JScrollBar(orientation:
the frame. Create a. vertical
the center +of visibleAmount scroll int, value: Creates a scroll

• ScrollBarDemo.java
int, extent: int, min: int, max: int) minimum, an
bar scroll baritsand
is set to place it in
maximum the east
value, the of
leftthe frame.
side of theCreate a horizontal
bubble scroll, and
is at maximum bar and
the place it is at
right side
+addAdjustmentListener(listener: Adds an Adjus
in the south
maximum of the frame.
+ visibleAmount . AdjustmentListener): void
2. Process the event.
rollBar has the following properties, as shown in Figure 17.27.
Create listeners to implement the adjustmentValueChanged handler to move Fthe IGURE 17.27 JScrollBar enables you to select from a range of v
Whenmessage
the user changes the value of the scroll bar,
according to the bar movement in the scroll bars. the scroll bar fires an instance of
ustmentEvent, which is passed to every registered listener. An object that wishes to be
ied of changes to the scroll bar’s value must implement the adjustmentValueChanged
Listing 17.10 gives a program that uses horizontal and vertical sc
od in the java.awt.event.AdjustmentListener interface. sage displayed on a panel. The horizontal scroll bar is used to move
the message to right and left (lines 44–54).
The maximum value of the vertical scroll bar corresponds to the height of the panel, and the
maximum value of the horizontal scroll bar corresponds to the width of the panel. The ratio
between the current and maximum values of the horizontal scroll bar is the same as the ratio 600 Chapter 17 Creating Graphical User Interf
between the x value and the width of the message panel. Similarly, the ratio between the

Slider
current and maximum values of the vertical scroll bar is the same as the ratio between the y
value and the height of the message panel. The x-coordinate and y-coordinate are set in javax.swing.JComponent
response to the scroll bar adjustments (lines 39, 50).

17.11 Sliders javax.swing.JSlider


JSlider is similar to JScrollBar, but JSlider has more properties and can appear in
many forms. Figure 17.29 shows two sliders. -maximum: int The
-minimum: int The
-value: int The
-orientation: int The
MessagePanel Vertical slider -paintLabels: boolean Tru
-paintTicks: boolean Tru
-paintTrack: boolean Tru
Horizontal slider -majorTickSpacing: int The
-minorTickSpacing: int The
FIGURE 17.29 The sliders move the message on a panel horizontally and vertically. -inverted: boolean Tru
n

JSlider lets the user graphically select a value by sliding a knob within a bounded inter- +JSlider() Cre
val. The slider can show both major tick marks and minor tick marks between them. The num- +JSlider(min: int, max: int) Cre
ber of pixels between the tick marks is controlled by the majorTickSpacing and +JSlider(min: int, max: int, value: int) Cre
minorTickSpacing properties. Sliders can be displayed horizontally or vertically, with or +JSlider(orientation: int) Cre
without ticks, and with or without labels. The frequently used constructors and properties in +JSlider(orientation: int, min: int, max: Cre
JSlider are shown in Figure 17.30. int, value: int)

• SliderDemo.java
+addChangeListener(listener: Add
Note ChangeListener) :void
The values of a vertical scroll bar increase from top to bottom, but the values of a vertical slider
decrease from top to bottom by default.
FIGURE 17.30 JSlider enables you to select from a range
Note
All the properties listed in Figure 17.30 have the associated get and set methods, which are omit- When the user changes t
ted for brevity. By convention, the get method for a Boolean property is named
is<PropertyName>(). In the JSlider class, the get methods for paintLabels,
javax.swing.event.Change
paintTicks, paintTrack, and inverted are getPaintLabels(), getPaintTicks(), object that wishes to be notif
and the main frame is called the main window.
To create a subwindow from an application, you need to define a subclass of JFrame
that specifies the task and tells the new window what to do. You can then create an instance
of this subclass in the application and launch the new window by setting the frame instance

Multiple Windows
to be visible.
Listing 17.12 gives a program that creates a main window with a text area in the scroll pane
and a button named Show Histogram. When the user clicks the button, a new window appears
that displays a histogram to show the occurrences of the letters in the text area. Figure 17.31
contains a sample run of the program.

FIGURE 17.31 The histogram is displayed in a separate frame.

• MultipleWindowsDemo.java
Here are the major steps in the program:
1. Create a main class for the frame named MultipleWindowsDemo in Listing 17.12.
Add a text area inside a scroll pane, and place the scroll pane in the center of the frame.

• Histogram.java
Create a button Show Histogram and place it in the south of the frame.
2. Create a subclass of JPanel named Histogram in Listing 17.13. The class contains a
data field named count of the int[] type, which counts the occurrences of 26 letters.
The values in count are displayed in the histogram.
3. Implement the actionPerformed handler in MultipleWindowsDemo, as follows:
a. Create an instance of Histogram. Count the letters in the text area and pass the
PopupMenu 34.3 Popup Menus 1157

menu is displayed when the popup trigger is issued on the text area.

ne and add a text area into it. Place the scroll pane in the center of the

tionPerformed handler to process the events from the menu items.

• PopupMenuDemo.java
usePressed and mouseReleased methods to process the events for
ggers.

pupMenuDemo.java
ng.*;
*;
ToolBar
• A JToolBar is a container that groups several
components — usually buttons with icons —
into a row or column. Often, tool bars provide
easy access to functionality that is also in menus.
How to Use Actions describes how to provide
the same functionality in menu items and tool bar
buttons.

77
To use JToolBar

• Create a JToolBar, add it to the JFrame


• Create and add JButtons and other components
to the JToolBar

• Add ActionListeners to the JButtons


ToolBarDemo.java
78
Dialog
Dialogs

• Modal dialogs block all other interaction.


• Forces a response from the user.
• Non-modal dialogs allow other interaction.
• This is sometimes desirable.
• May be difficult to avoid inconsistencies.

80
JDialog

• Every dialog is dependent on a frame. When that frame is


destroyed, so are its dependent dialogs. When the frame is
iconified, its dependent dialogs disappear from the screen.
When the frame is deiconified, its dependent dialogs return
to the screen. The Swing automatically provides this behavior.

• A dialog can be modal. When a modal dialog is visible, it


blocks user input to all other windows in the program. The
JDialogs that JOptionPane creates are modal. To create a non-
modal dialog, you must use the JDialog class directly.
81
Code for JDialog
• To define a dialog:
public class DlgReport extends JDialog {
public DlgReport(JFrame frame... ) {
super(frame,"The Title",true);
• To use that dialog:
DlgReport dlg = new DlgReport(theFrame,...);
dlg.pack();
dlg.setVisible(true);
82
Code for Dialogs

• Write your own code to describe the


components in the dialog, and define the event
handlers

• Write get/set functions to access the variables


JOptionPane standard dialogs 34.6 JOptionPane

Icon Message

Input Icon Message

• Message
Buttons dialog Button

• Message text plus an OK button.


(a) (b)

FIGURE 34.10 (a) A JOptionPane dialog can display an icon, a message, an input, and op-

• Confirm dialog
tion buttons. (b) The message dialog displays a message and waits for the user to click OK.

For example, you can use the following method to create a message dialog box, as shown

• Yes, No, Cancel options.


in Figure 34.10(b):

• Input dialog
JOptionPane.showMessageDialog(null, "SSN not found",
"For Your Information", JOptionPane.INFORMATION_MESSAGE);

• Message text and an input field.


34.6.1 Message Dialogs
A message dialog box displays a message that alerts the user and waits for the user to click the

• Variations are possible.


OK button to close the dialog. The methods for creating message dialogs are:

public static void showMessageDialog(Component parentComponent,


Object message)
public static void showMessageDialog(Component parentComponent,
84
Object message,
JOptionPane
• JOptionPane makes it easy to pop up a standard
dialog box that prompts users for a value or
informs them of something.

Method Name Description


showConfirmDialog Asks a confirming question, like yes/no/cancel.

showInputDialog Prompt for some input.


showMessageDialog Tell the user about something that has happened

showOptionDialog The Grand Unification of the above three.


85
Message Dialogs
• JOptionPane.ERROR_MESSAGE
• JOptionPane.INFORMATION_MESSAGE
• JOptionPane.PLAIN_MESSAGE
• JOptionPane.WARNING_MESSAGE

1166 Chapter 34 Menus, Toolbars, and Dialogs
JOptionPane.QUESTION_MESSAGE

FIGURE 34.11 There are five types of message dialog boxes.


A message dialog
private void showAbout()
{
JOptionPane.showMessageDialog(frame,
"ImageViewer\n" + VERSION,
"About ImageViewer",
JOptionPane.INFORMATION_MESSAGE);
}

87
ConfirmDialogs
34.6 JOptionPa
The parameters parentComponent, message, title, icon, and messageType are the
same as in the showMessageDialog method. The default value for title is “Select an Op-
• JOptionPane.YES_NO_OPTION
tion” and for messageType is QUESTION_MESSAGE. The optionType determines which
buttons are displayed in the dialog. The possible values are:

• JOptionPane.YES_NO_CANCEL_OPTION
JOptionPane.YES_NO_OPTION
JOptionPane.YES_NO_CANCEL_OPTION

• JOptionPane.OK_CANCEL_OPTION
JOptionPane.OK_CANCEL_OPTION

Figure 34.13 shows the confirmation dialogs with these options.

FIGURE 34.13 The confirmation dialog displays a question and three types of option but-
InputDialogs
1168 Chapter 34 Menus, Toolbars, and Dialogs
The first three methods listed above use a text field for input, as shown in Figure 34.14(a) .
The last method listed above specifies an array of Object type as selection values in addition
to an object specified as an initial selection. The first three methods return a String that is
entered from the text field in the input dialog. The last method returns an Object selected
from a combo box or a list. The input dialog displays a combo box if there are fewer than
twenty selection values, as shown in Figure 34.14(b); it displays a list if there are twenty or
more selection values, as shown in Figure 34.14(c).

List List List

(a) Text field (b) Combo box (c) List

FIGURE 34.14 (a) When creating an input dialog without specifying selection values, the input dialog displays a text
field for data entry. (b) When creating an input dialog with selection values, the input dialog displays a combo box if
there are fewer than twenty selection values. (c) When creating an input dialog with selection values, the input dialog dis-
plays a list if there are twenty or more selection values.
Code for JOptionPane

JOptionPane.showMessageDialog(theFrame,"(C)2007 BA5AG");
String name = JOptionPane.showInputDialog(theFrame,"Input the name:","Search
Author",JOptionPane.QUESTION_MESSAGE);
if ( JOptionPane.showConfirmDialog( this, "delete?", "delete?",
JOptionPane.YES_NO_OPTION ) == JOptionPane.NO_OPTION )

JOptionPaneDemo.java
90
Create Your Dialog

• extend class JDialog


• set modal public ColorDialog(java.awt.Frame parent, boolean modal) {
• set visible super(parent, modal);

• dispose
ColorDialog.java
JTable
• With the JTable class you can display tables of
data, optionally allowing the user to edit the data.
JTable does not contain or cache data; it is simply
a view of your data.

92
TableModel

93
Code for JTable

JTable table = new JTable(new MyDataModel());


JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);

94
AbstractTableModel

public int getColumnCount()


public int getRowCount()
public String getColumnName(int col)
public Object getValueAt(int row, int col)
public boolean isCellEditable(int row, int col)
public void setValueAt(Object value, int row, int col)

95
The imageviewer project

96
Image processing

97
Class responsibilities
•ImageViewer
• Sets up the GUI structure.
•ImageFileManager
• Static methods for image file loading and saving.
•ImagePanel
• Displays the image within the GUI.
•OFImage
• Models a 2D image.
98
OFImage
• Our subclass of BufferedImage.
• Represents a 2D array of pixels.
• Important methods:
–getPixel, setPixel
–getWidth, getHeight

• Each pixel has a color.


• We use java.awt.Color.
99
Adding an ImagePanel
public class ImageViewer
{
private JFrame frame;
private ImagePanel imagePanel;

private void makeFrame()


{
Container contentPane = frame.getContentPane();
imagePanel = new ImagePanel();
contentPane.add(imagePanel);
}


}

100
Loading an image
public class ImageViewer
{
private JFrame frame;
private ImagePanel imagePanel;

private void openFile()


{
File selectedFile = …;
OFImage image =
ImageFileManager.loadImage(selectedFile);
imagePanel.setImage(image);
frame.pack();
}


}
101
Image filters

• Functions applied to the whole image.


int height = getHeight();
int width = getWidth();
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
Color pixel = getPixel(x, y);
alter the pixel's color value;
setPixel(x, y, pixel);
}
}

102
Adding further filters
private void makeLighter()
{
if(currentImage != null) {
currentImage.lighter();
frame.repaint();
showStatus("Applied: lighter");
}
Code duplication?
else {
showStatus("No image loaded.");
Refactor!
}
}

private void threshold()


{
if(currentImage != null) {
currentImage.threshold();
frame.repaint();
showStatus("Applied: threshold");
}
else {
showStatus("No image loaded.");
}
}
103
Adding further filters

• Define a Filter superclass (abstract).


• Create function-specific subclasses.
• Create a collection of subclass instances in
ImageViewer.
• Define a generic applyFilter method.
• See imageviewer2-0.

104
imageviewer2-0

105
Buttons and nested layouts

A GridLayout inside
a FlowLayout inside
a BorderLayout.

106
Borders

• Used to add decoration around components.


• Defined in javax.swing.border
–BevelBorder, CompoundBorder,
EmptyBorder, EtchedBorder,
TitledBorder.

107
Adding spacing
JPanel contentPane = (JPanel)frame.getContentPane();
contentPane.setBorder(new EmptyBorder(6, 6, 6, 6));

// Specify the layout manager with nice spacing


contentPane.setLayout(new BorderLayout(6, 6));

imagePanel = new ImagePanel();


imagePanel.setBorder(new EtchedBorder());
contentPane.add(imagePanel, BorderLayout.CENTER);

108

You might also like