6 GUI - The Model of Design
6 GUI - The Model of 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.
•
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
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.
FontMetrics
Graphics
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
Note
JFrame
11
Creating a frame
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*/
public ImageViewer()
makeFrame();
12
code for JFrame
13
Elements of a frame
Title Window controls
Menu bar
Content pane
14
JFrame
javax.swing.JFrame
• 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
drawing strings and +fillOval(x: int, y: int, w: int, h: int): void Draw
p
drawLine
(x1, y1)
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
(x, y) (x, y)
Color
• 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
(x, y) (x, y)
h h
w w
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 drawing method opens the polygon by drawing lines between point (x[i], y[i]) and
(x[0], y[0])
(x[0], y[0])
(x[1], y[1]) (x[1], y[1])
(x[3], y[3]) (x[3], y[3])
FIGURE 15.15 The drawPolygon method draws a polygon, and the polyLine method draws a polyline.
• drawPolygon(Polygon polygon);
fillPolygon(Polygon polygon);
Another way polygon
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),
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
MessagePanel.java
TestMessagePanel.java
Images as Icons
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
/**
*/
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");
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.
-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).
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.
-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
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
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
javax.swing.JComponent
Titled border
Line border
FIGURE 12.12 The font, color, border, and tool tip text are set in the message panel.
(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);
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
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
FIGURE 16.3 A listener must be an instance of a listener interface and must be registered with a source component.
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
-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
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
• 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.
• 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
• 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
• 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
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).
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.
• 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
• 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
80
JDialog
Icon Message
• Message
Buttons dialog Button
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
• Input dialog
JOptionPane.showMessageDialog(null, "SSN not found",
"For Your Information", 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 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).
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
• 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
94
AbstractTableModel
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
…
}
100
Loading an image
public class ImageViewer
{
private JFrame frame;
private ImagePanel imagePanel;
…
}
101
Image filters
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!
}
}
104
imageviewer2-0
105
Buttons and nested layouts
A GridLayout inside
a FlowLayout inside
a BorderLayout.
106
Borders
107
Adding spacing
JPanel contentPane = (JPanel)frame.getContentPane();
contentPane.setBorder(new EmptyBorder(6, 6, 6, 6));
108