Document 7675392

Download Report

Transcript Document 7675392

Chapter 13
Creating User Interfaces
Prerequisites for Part III
Chapter 8 Inheritance and Polymorphism
Chapter 11 Getting Started with GUI Programming
Chapter 12 Event-Driven Programming
Chapter 13 Creating User Interfaces
Chapter 14 Applets, Images, Audio
Chapter 9 Abstract Classes and Interfaces
…Starry starry night
flaming flowers that brightly blaze
swirling clouds in violet haze
reflect in Vincent's eyes of China blue.
Colors changing hue
morning fields of amber grain
weathered faces lined in pain
are smoothed beneath the artist's loving hand.
And now I understand
what you tried to say to me
and how you suffered for your sanity
and how you tried to set them free….
Liang,Introduction to Java Programming,revised by Dai-kaiyu
1
Objectives
 To create graphical user interfaces with various user-interface
components: JButton, JCheckBox, JRadioButton, JLabel,
JTextField, JTextArea, JComboBox, JList, JScrollBar, and JSlider
(§13.2 – 13.12).
 To create listeners for various types of events (§13.2 – 13.12).
 To use borders to visually group user-interface components
(§13.2).
 To create image icons using the ImageIcon class (§13.3).
 To display multiple windows in an application (§13.13).
 To know how to create menu
Liang,Introduction to Java Programming,revised by Dai-kaiyu
2
Components Covered in the Chapter
Introduces the frequently used GUI components
Uses borders and icons
JButton
Component
Container
JComponent
AbstractButton
JCheckBox
JToggleButton
JRadioButton
JLabel
JTextField
JTextComponent
JTextArea
JComboBox
JList
JScrollBar
JSlider
Liang,Introduction to Java Programming,revised by Dai-kaiyu
3
java.awt.Component
+getFont(): java.awt.Font
Returns the font of this component.
+setFont(f: java.awt.Font): void
Sets the font of this component.
+getBackground(): java.awt.Color
Returns the background color of this component.
+setBackground(c: Color): void
Sets the background color of this component.
+getForeground(): java.awt.Color
Returns the foreground color of this component.
+setForeground(c: Color): void
Sets the foreground color of this component.
+getWidth(): int
Returns the width of this component.
+getHeight(): int
Returns the height of this component.
+getPreferredSize(): Dimension
Returns the preferred size of this component.
+setPreferredSize(d: Dimension) : void
Sets the preferred size of this component.
+isVisible(): boolean
Indicates whether this component is visible.
+setVisible(b: boolean): void
Shows or hides this component.
java.awt.Container
+add(comp: Component): Component
Appends a component to the container.
+add(comp: Component, index: int): Component Adds a component to the container with the specified index.
Removes the component from the container.
+remove(comp: Component): void
+getLayout(): LayoutManager
Returns the layout manager for this container.
+setLayout(l: LayoutManager): void
Sets the layout manager for this container.
+paintComponents(g: Graphics): void
Paints each of the components in this container.
javax.swing.JComponent
+getToolTipText(): String
Returns the tool tip text for this component. Tool tip text is displayed
when the mouse points on the component without clicking.
+setToolTipText(test: String): void
Sets a new tool tip text for this component.
+getBorder(): javax.swing.border.Border
Returns the border for this component.
+setBorder(border: Border): void
Sets a new border for this component.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
4
Borders
You can set a border on any object of the JComponent
class. Swing has several types of borders. To create a
titled border, use
new TitledBorder(String title).
To create a line border, use
new LineBorder(Color color, int width),
where width specifies the thickness of the line.
For example, the following code displays a titled border
on a panel:
JPanel panel = new JPanel();
panel.setBorder(new TitleBorder(“My Panel”));
Liang,Introduction to Java Programming,revised by Dai-kaiyu
5
Test Swing Common Features
Component Properties
JComponent Properties
 font
 background
 foreground
 preferredSize
 minimumSize
 maximumSize
toolTipText
border
TestSwingCommonFeatures
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
6
Buttons
A button is a component that triggers an action
event when clicked.
Swing provides regular buttons, toggle buttons,
check box buttons, and radio buttons.
The common features of these buttons are
represented in javax.swing.AbstractButton.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
7
javax.swing.JComponent
javax.swing.AbstractButton
+getActionCommand(): String
Returns the action command of this button.
+setActionCommand(s: String): void
Sets a new action command for this button.
+getText(): String
Returns the button’s text (i.e., the text label on the button).
+setText(text: String): void
Sets the button’s text.
+getIcon(): javax.swing.Icon
Returns the button’s default icon.
+setIcon(icon: Icon): void
Sets the button's default icon. This icon is also used as the "pressed" and
"disabled" icon if there is no explicitly set pressed icon.
+getPressedIcon(): javax.swing.Icon
Returns the pressed icon (displayed when the button is pressed).
+setPressedIcon(pressedIcon: Icon): void Sets a pressed icon for the button.
+getRolloverIcon(): javax.swing.Icon
Returns the rollover icon (displayed when the mouse is over the button).
+setRolloverIcon(pressedIcon: Icon):
void
Sets a rollover icon for the button.
+getMnemonic(): int
Returns the mnemonic key value of this button. You can select the button
by pressing the ALT key and the mnemonic key at the same time.
+setMnemonic(mnemonic: int): void
Sets a mnemonic key value of this button.
+getHorizontalAlignment(): int
Returns the horizontal alignment of the icon and text on the button.
+setHorizontalAlignment(alignment: int): Sets the horizontal alignment of the icon and text. (default: CENTER)
void
+getHorizontalTextPosition(): int
Returns the horizontal text position relative to the icon on the button.
+setHorizontalTextPosition(position: int): Sets the horizontal text position of the text relative to the icon. (default:
void
RIGHT)
+getVerticalAlignment(): int
Returns the vertical alignment of the icon and text on the button.
+setVerticalAlignment(vAlignment: int):
void
Sets the vertical alignment of the icon and text. (default: CENTER).
+getVerticalTextPosition(): int
Returns the vertical text position relative to the icon on the button.
+setVerticalTextPosition(position: int) :
void
Sets the vertical text position of the text relative to the icon. (default:
CENTER)
+isBorderPainted(): Boolean
Indicates whether the border of the button is painted.
+setBorderPainted(b: boolean): void
Draws or hides the border of the button. By default, a regular button’s
border is painted, but the border for a check box and a radio button is
not painted.
+getIconTextGap(): int
Returns the gap between the text and the icon on the button. (JDK 1.4)
+setIconTextGap(iconTextGap: int): void Sets a gap between the text and the icon on the button. (JDK 1.4)
+isSelected(): boolean
Returns the state of the button. True if the check box or radio button is
Liang,Introduction to Java Programming,revised by Dai-kaiyu
selected, false if it's not.
+setSelected(b: boolean): void
Sets the state for the check box or radio button.
8
JButton
JButton inherits AbstractButton and provides several
constructors to create buttons.
javax.swing.AbstractButton
javax.swing.JButton
+JButton()
Creates a default button with no text and icon.
+JButton(icon: javax.swing.Icon)
Creates a button with an icon.
+JButton(text: String)
Creates a button with text.
+JButton(text: String, icon: Icon)
Creates a button with text and an icon.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
9
JButton Constructors
The following are JButton constructors:
JButton()
JButton(String text)
JButton(String text, Icon icon)
JButton(Icon icon)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
10
JButton Properties
 text
 icon
 mnemonic
 horizontalAlignment
 verticalAlignment
 horizontalTextPosition
 verticalTextPosition
 iconTextGap
Liang,Introduction to Java Programming,revised by Dai-kaiyu
11
Icons
An icon is a fixed-size picture; typically it
is small and used to decorate components.
 javax.swing.Icon is an interface. To create
an image, use its concrete class
javax.swing.ImageIcon. For example, the
following statement creates an icon from an
image file:
Icon icon = new ImageIcon("photo.gif");
TestButtonIcons
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
12
Default Icons, Pressed Icon, and
Rollover Icon
A regular button has a default icon, pressed icon, and
rollover icon. Normally, you use the default icon.
All other icons are for special effects. A pressed icon is
displayed when a button is pressed and a rollover icon is
displayed when the mouse is over the button but pressed.
(A) Default icon
(B) Pressed icon
Liang,Introduction to Java Programming,revised by Dai-kaiyu
(C) Rollover icon
13
Horizontal Alignments
See figure 13.7
Horizontal alignment specifies how the icon and text are
placed horizontally on a button. You can set the horizontal
alignment using one of the five constants: LEADING, LEFT,
CENTER, RIGHT, TRAILING. At present, LEADING and
LEFT are the same and TRAILING and RIGHT are the
same. Future implementation may distinguish them. The
default horizontal alignment is SwingConstants.TRAILING.
Vertical Alignments
Vertical alignment specifies how the icon and text are placed
vertically on a button. You can set the vertical alignment
using one of the three constants: TOP, CENTER, BOTTOM.
The default vertical alignment is SwingConstants.CENTER.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
14
Horizontal Text Positions
Horizontal text position specifies the horizontal
position of the text relative to the icon.
You can set the horizontal text position using one
of the five constants: LEADING, LEFT, CENTER,
RIGHT, TRAILING. The default horizontal text
position is SwingConstants.RIGHT.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
15
Vertical Text Positions
Vertical text position specifies the vertical
position of the text relative to the icon.
You can set the vertical text position using
one of the three constants: TOP, CENTER.
The default vertical text position is
SwingConstants.CENTER.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
16
Example 13.1: Using Buttons
Write a program that displays a
message on a panel and uses
two buttons, <= and =>, to move
the message on the panel to the
left or right.
ButtonDemo
Run
MessagePanel
JButton
JButton
setMnemonic (using alt key)
getSource() to judge the source UI
Liang,Introduction to Java Programming,revised by Dai-kaiyu
17
JCheckBox
JCheckBox inherits all the properties such as text, icon,
mnemonic, verticalAlignment, horizontalAlignment,
horizontalTextPosition, verticalTextPosition, and
selected from AbstractButton, and provides several
constructors to create check boxes.
javax.swing.AbstractButton
javax.swing.JToggleButton
javax.swing.JCheckBox
+JCheckBox()
Creates a default check box button with no text and icon.
+JCheckBox(text: String)
Creates a check box with text.
+JCheckBox(text: String, selected:
boolean)
Creates a check box with text and specifies whether the check box is
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,
selected: boolean)
Creates a check box with text and an icon, and specifies whether the check
box is initially selected.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
18
Example 13.2: Using Check Boxes
Add three check boxes named
Centered, Bold, and Italic into
Example 13.1 to let the user
specify whether the message
is centered, bold, or italic.
ButtonDemo
CheckBoxDemo
CheckBoxDemo
Run
Liang,Introduction to Java Programming,revised by Dai-kaiyu
19
JRadioButton
Radio buttons are variations of check boxes. They are
often used in the group, where only one button is
checked at a time.
javax.swing.AbstractButton
javax.swing.JToggleButton
javax.swing.JRadioButton
+JRadioButton()
Creates a default radio button with no text and icon.
+JRadioButton(text: String)
Creates a radio button with text.
+JRadioButton(text: String, selected:
boolean)
Creates a radio button with text and specifies whether the radio button is
initially selected.
+JRadioButton(icon: Icon)
Creates a radio button with an icon.
+JRadioButton(text: String, icon: Icon)
Creates a radio button with text and an icon.
+JRadioButton(text: String, icon: Icon,
selected: boolean)
Creates a radio button with text and an icon, and specifies whether the radio
button is initially selected.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
20
Grouping Radio Buttons
ButtonGroup btg = new ButtonGroup();
btg.add(jrb1);
btg.add(jrb2);
Liang,Introduction to Java Programming,revised by Dai-kaiyu
21
Example 13.3: Using Radio Buttons
Add three radio buttons
named Red, Green, and
Blue into the preceding
example to let the user
choose the color of the
message.
ButtonDemo
CheckBoxDemo
RadioButtonDemo
RadioButtonDemo
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
22
JLabel
A label is a
display area
for a short
text, an image,
or both.
javax.swing.JComponent
javax.swing.JLabel
+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,
hAlignment: int)
Creates a label with text, an icon and the specified horizontal alignment.
+JLabel(text: String, hAlignment: int)
Creates a label with text and the specified horizontal alignment.
+getText(): String
Returns the label’s text.
+setText(text: String): void
Sets the label’s text.
+getIcon(): javax.swing.Icon
Returns the label’s image icon.
+setIcon(icon: Icon): void
Sets an image icon on the label.
+getHorizontalAlignment(): int
Returns the horizontal alignment of the text and icon on the label.
+setHorizontalAlignment(alignment: int): Sets the horizontal alignment – same as for buttons.
void
+getHorizontalTextPosition(): int
Returns the horizontal text position relative to the icon on the label.
+setHorizontalTextPosition(textPosition: Sets the horizontal text position – same as for buttons.
int): void
+getVerticalAlignment(): int
Returns the vertical alignment of the text and icon on the label.
+setVerticalAlignment(vAlignment: int): Sets the vertical alignment – same as for buttons.
void
+getVerticalTextPosition(): int
Returns the vertical text position relative to the icon on the label.
+setVerticalTextPosition(vTextPosition:
int) : void
Sets the vertical text position – same as for buttons
+getIconTextGap(): int
Returns the gap between the text and the icon on the label. (JDK 1.4)
+setIconTextGap(iconTextGap:
int):
void
Sets a gap between
the text and the icon on the label. (JDK 1.4)23
Liang,Introduction to Java Programming,revised
by Dai-kaiyu
JLabel Constructors
The constructors for labels are as follows:
JLabel()
JLabel(String text, int horizontalAlignment)
JLabel(String text)
JLabel(Icon icon)
JLabel(Icon icon, int horizontalAlignment)
JLabel(String text, Icon icon, int
horizontalAlignment)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
24
JLabel Properties
JLabel inherits all the properties from
JComponent and has many properties
similar to the ones in JButton, such as
text, icon, horizontalAlignment,
verticalAlignment,
horizontalTextPosition,
verticalTextPosition, and iconTextGap.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
25
Using Labels
// Create an image icon from image file
ImageIcon icon = new ImageIcon("image/grapes.gif");
// Create a label with text, an icon,
// with centered horizontal alignment
JLabel jlbl = new JLabel("Grapes", icon,
SwingConstants.CENTER);
// Set label's text alignment and gap between text and icon
jlbl.setHorizontalTextPosition(SwingConstants.CENTER);
jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);
jlbl.setIconTextGap(5);
Liang,Introduction to Java Programming,revised by Dai-kaiyu
26
JTextField
A text field is an input area where the user
can type in characters. Text fields are useful
in that they enable the user to enter in variable data
(such as a name or a description).
javax.swing.text.JTextComponent
+getText(): String
Returns the text contained in this text component.
+setText(text: String): void
Sets a text in this text component.
+isEditable(): boolean
Indicates whether this text component is editable.
+setEditable(b: boolean): void
Sets the text component editable or prevents it from being edited.
(default: true)
javax.swing.JTextField
+JTextField()
Creates a default empty text field with number of columns set to 0.
+JTextField(column: int)
Creates an empty text field with specified number of columns.
+JTextField(text: String)
Creates a text field initialized with the specified text.
+JTextField(text: String, columns: int)
Creates a text field initialized with the specified text and columns.
+getColumns(): int
Returns the number of columns in this text field.
+setColumns(columns: int): void
Sets the number of columns in this text field.
+getHorizontalAlignment(): int
Returns the horizontal alignment of this text field.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
+setHorizontalAlignment(alignment: int): void Sets the horizontal alignment for this text field. (default: LEFT)
27
JTextField Constructors
 JTextField(int columns)
Creates an empty text field with the
specified number of columns.
 JTextField(String text)
Creates a text field initialized with the
specified text.
 JTextField(String text, int columns)
Creates a text field initialized with the
specified text and the column size.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
28
JTextField Properties
text
horizontalAlignment
editable
columns
Liang,Introduction to Java Programming,revised by Dai-kaiyu
29
JTextField Methods
 getText()
Returns the string from the text field.
 setText(String text)
Puts the given string in the text field.
 setEditable(boolean editable)
Enables or disables the text field to be edited. By default,
editable is true.
 setColumns(int)
Sets the number of columns in this text field.
The length of the text field is changeable.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
30
Example 13.4: Using Text Fields
Add a text field to the
preceding example to
let the user set a new
message.
ActionListener
ButtonDemo
CheckBoxDemo
RadioButtonDemo
TextFieldDemo
JFrame
frame.pack() automatically sizes up the frame
according to the size of the components places
in it
TextFieldDemo
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
31
JTextArea
JTextAreaenables the user to enter multiple lines of text.
javax.swing.text.JTextComponent
javax.swing.JTextArea
+JTextArea()
Creates a default empty text area.
+JTextArea(rows: int, columns: int)
Creates an empty text area with the specified number of rows and columns.
+JTextArea(text: String)
Creates a new text area with the 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.
+append(s: String): void
Appends the string to text in the text area.
+insert(s: String, pos: int): void
Inserts string s in the specified position in the text area.
+replaceRange(s: String, start: int, end: int): void Replaces partial text in the range from position start to end with string s.
+getColumns(): int
Returns the number of columns in this text area.
+setColumns(columns: int): void
Sets the number of columns in this text area.
+getRows(): int
Returns the number of rows in this text area.
+setRows(rows: int): void
Sets the number of rows in this text area.
+getLineCount(): int
Returns the actual number of lines contained in the text area.
+getTabSize(): int
Returns the number of characters used to expand tabs in this text area.
+setTabSize(size: int): void
Sets the number of characters to expand tabs to. (default: 8)
+getLineWrap(): boolean
Indicates whether the line in the text area is automatically wrapped.
+setLineWrap(wrap: boolean): void
Sets the line-wrapping policy of the text area. (default: false)
+getWrapStyleWord(): boolean
Indicates whether the line is wrapped on words or characters.
+setWrapStyleWord(word: boolean): void
Sets the style of wrapping used if the text area is wrapping lines. The default
value is false, which indicates that the line is wrapped on characters.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
32
JTextArea Constructors
 JTextArea(int rows, int columns)
Creates a text area with the specified
number of rows and columns.
 JTextArea(String s, int rows, int columns)
Creates a text area with the initial text and
the number of rows and columns specified.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
33
JTextArea Properties
text
editable
columns
lineWrap
wrapStyleWord
rows
lineCount
tabSize
Liang,Introduction to Java Programming,revised by Dai-kaiyu
34
Example 13.5 Using Text Areas
This example gives a program that displays
an image in a label, a title in a label, and a
text in a text area.
JPanel
JFrame
-char token
-char token
+getToken
DescriptionPanel
+setToken
+paintComponet
-jlblImage: JLabel
+mouseClicked
-jlblTitle: JLabel
-jtaTextDescription: JTextArea
1
1
+getToken
TextAreaDemo
+setToken
+paintComponet
+mouseClicked
+setImageIcon(icon: ImageIcon): void
+setTitle(title: String): void
+setTextDescription(text: String): void
+getMinimumSize(): Dimension
Liang,Introduction to Java Programming,revised by Dai-kaiyu
35
Example 13.5, cont.
TextAreaDemo
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
36
JComboBox
A combo box is a simple list of items from which the
user can choose. It performs basically the same
function as a list, but can get only one value.
javax.swing.JComponent
javax.swing.JComboBox
+JComboBox()
Creates a default empty combo box.
+JComboBox(items: Object[])
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.
+getItemCount(): int
Returns the number of items in the combo box.
+getSelectedIndex(): int
Returns the index of the selected item.
+setSelectedIndex(index: int): void
Sets the selected index in the combo box.
+getSelectedItem(): Object
Returns the selected item.
+setSelectedItem(item: Object): void
Sets the selected item in the combo box.
+removeItem(anObject: Object): void Removes an item from the item list.
Removes the item at the specified index in the combo box.
+removeItemAt(anIndex: int): void
+removeAllItems(): void
Removes all items in the combo box.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
37
JComboBox Methods
To add an item to a JComboBox jcbo, use
jcbo.addItem(Object item)
To get an item from JComboBox jcbo, use
jcbo.getItem()
Liang,Introduction to Java Programming,revised by Dai-kaiyu
38
Using the
itemStateChanged Handler
When a choice is checked or unchecked,
itemStateChanged() for ItemEvent is
invoked as well as the actionPerformed()
handler for ActionEvent.
public void itemStateChanged(ItemEvent e) {
// Make sure the source is a combo box
if (e.getSource() instanceof JComboBox)
String s = (String)e.getItem();
}
Liang,Introduction to Java Programming,revised by Dai-kaiyu
39
Example 13.6: Using Combo Boxes
This example lets
users view an
image and a
description of a
country's flag by
selecting the
country from a
combo box.
ComboBoxDemo
Run
Liang,Introduction to Java Programming,revised by Dai-kaiyu
40
JList
A list is a component that performs basically the same function
as a combo box, but it enables the user to choose a single value
or multiple values.
javax.swing.JComponent
javax.swing.JList
+JList()
Creates a default empty list.
+JList(items: Object[])
Creates a list that contains the elements in the specified array.
+getSelectedIndex(): int
Returns the index of the first selected item.
+setSelectedIndex(index: int): void
Selects the cell at the specified index.
+getSelectedIndices(): int[]
Returns an array of all of the selected indices in increasing order.
+setSelectedIndices(indices: int[]): void Selects the cells at the specified indices.
+getSelectedValue(): Object
Returns the first selected item in the list.
+getSelectedValues(): Object[]
Returns an array of the values for the selected cells in increasing index order.
+getVisibleRowCount(): int
Returns the number of visible rows displayed without a scrollbar. (default: 8)
+setVisibleRowCount(count: int): void
Sets the preferred number of visible rows displayed without a scrollbar.
+getSelectionBackground(): Color
Returns the background color of the selected cells.
+setSelectionBackground(c: Color): void Sets the background color of the selected cells.
+getSelectionForeground(): Color
Returns the foreground color of the selected cells.
+setSelectionForeground(c: Color): void Sets the foreground color of the selected cells.
+getSelectionMode(): int
Liang,Introduction
to the
Javaselection
Programming,revised
bylist.
Dai-kaiyu
Returns
mode for the
+setSelectionMode(selectionMode: int): Sets the selection mode for the list.
41
JList Constructors
 JList()
Creates an empty list.
 JList(Object[] stringItems)
Creates a new list initialized with items.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
42
JList Properties
selectedIndexd
selectedIndices
selectedValue
selectedValues
selectionMode
visibleRowCount
Liang,Introduction to Java Programming,revised by Dai-kaiyu
43
Example 13.7: Using Lists
This example
gives a program
that lets users
select countries in
a list and display
the flags of the
selected countries
in the labels.
Jlabel.setIcon(null);
ListDemo
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
44
JScrollBar
A scroll bar is a control that enables the user to select from
a range of values. The scrollbar appears in two styles:
horizontal and vertical.
javax.swing.JComponent
javax.swing.JScrollBar
+JScrollBar()
Creates a default vertical scroll bar.
+JScrollBar(orientation: int)
Creates a scroll bar with the specified orientation.
+JScrollBar(orientation: int, value: int,
extent: int, min: int, max: int)
Creates a scrollbar with the specified orientation, value, extent, minimum, and
maximum.
+getBlockIncrement(): int
Returns the block increment.
+setBlockIncrement(increment: int): void Sets a new block increment. (default: 10)
+getMaximum(): int
Returns the maximum value represented by the scroll bar.
+setMaximum(maximum: int): void
Sets a new maximum. (default: 100)
+getMinimum(): int
Returns the minimum value represented by the scroll bar.
+setMinimum(minimum: int): void
Sets a new minimum. (default: 0)
+getOrientation(): int
Returns the orientation of the scroll bar.
+setOrientation(orientation: int): void
Sets a new orientation for the scroll bar.
+getUnitIncrement(): int
Returns the unit increment in the scroll bar.
+setUnitIncrement(increment: int): void
Sets a new unit increment in the scroll bar.
+getValue(): int
Returns the current value represented by the scroll bar.
+setValue(int value): void
Sets a new current value represented by the scroll bar.
+getVisibleAmount(): int
Returns the visible amount in the scroll bar.
+setVisibleAmount(extent: int): void
Sets a new visible amount for the scroll bar. (default: 10)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
45
Scroll Bar Properties
Minimal value
Maximal value
Block decrement
Block increment
Bubble
Unit decrement
Unit increment
Liang,Introduction to Java Programming,revised by Dai-kaiyu
46
Scroll Bar event-driven model
Generate AdjustmentEvent
Change the value of
JScrollBar
register
AdjustmentListener
adjustmentValueChanged
Liang,Introduction to Java Programming,revised by Dai-kaiyu
47
Example 13.8: Using Scrollbars
This example uses
horizontal and vertical
scrollbars to control a
message displayed on a
panel. The horizontal
scrollbar is used to move
the message to the left or
the right, and the vertical
scrollbar to move it up and
down.
ScrollBarDemo
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
48
JSlider
JSlider is similar to JScrollBar, but JSlider has more
properties and can appear in many forms.
javax.swing.JComponent
javax.swing.JSlider
+JSlider()
Creates a default horizontal slider.
+JSlider(min: int, max: int)
Creates a horizontal slider using the specified min and max.
+JSlider(min: int, max: int, value: int)
Creates a horizontal slider using the specified min, max, and value.
+JSlider(orientation: int)
Creates a slider with the specified orientation.
+JSlider(orientation: int, min: int, max:
int, value: int)
Creates a slider with the specified orientation, min, max, and value.
+getInverted(): boolean
Returns true if the value-range shown for the slider is reversed.
+setInverted(b: boolean): void
Sets true to reverse the value-range, and false to put the value range in the
normal order. (default: false)
+getMajorTickSpacing(): int
Returns the number of units between major ticks.
+setMajorTickSpacing(n: int): void
Sets the number of units between major ticks. (default: 0)
+getMinorTickSpacing(): int
Returns the number of units between minor ticks.
+setMinorTickSpacing(n: int): void
Sets the number of units between minor ticks. (default: 0)
+getMaximum(): int
Returns the maximum value represented by the slider.
+setMaximum(maximum: int): void
Sets a new maximum. (default: 100)
+getMinimum(): int
Returns the minimum value represented by the slider.
+setMinimum(minimum: int): void
Sets a new minimum. (default: 0)
+getOrientation(): int
Returns the orientation of the slider.
+setOrientation(orientation: int): void
Sets a new orientation for the slider.
+getPaintLabels(): boolean
Returns true if the labels are painted at tick marks.
+setPaintLabels(b: boolean): void
Sets a Boolean value to determine whether labels are painted. (default: false)
+getPaintTicks(): boolean
Returns true if the ticks are painted on the slider.
+setPaintTicks(b: boolean): void
Sets a Boolean value to determine whether ticks are painted. (default: false)
+getPaintTrack(): boolean
Returns true if the track are painted on the slider.
+setPaintTrack(b: boolean): void
Sets a Boolean value to determine whether tracks are painted. (default: true)
+getValue(): int
Returns the current value represented by the slider.
Liang,Introduction
to Java
Programming,revised
by Dai-kaiyu
+setValue(int
value):
void
Sets a new value represented by the slider.
49
Scroll Bar event-driven model
Generate ChangedEvent
Change the value of
JSlider
register
ChangeListener
stateChanged
Liang,Introduction to Java Programming,revised by Dai-kaiyu
50
Example 13.9: Using Sliders
Rewrite the preceding
program using the sliders
to control a message
displayed on a panel
instead of using scroll
bars.
jsldHort.setPaintLabels(true);
jsldHort.setPaintTicks(true);
jsldHort.setMajorTickSpacing(10);
jsldHort.setMinorTickSpacing(1);
jsldHort.setPaintTrack(false);
jsldVert.setInverted(true);
SliderDemo
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
51
Liang,Introduction to Java Programming,revised by Dai-kaiyu
52
Creating Multiple Windows
The following slides show step-by-step how to
create an additional window from an application
or applet.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
53
Creating Additional Windows, Step 1
Step 1: Create a subclass of JFrame (called a
SubFrame) that tells the new window what
to do. For example, all the GUI application
programs extend JFrame and are subclasses
of JFrame.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
54
Creating Additional Windows, Step 2
Step 2: Create an instance of SubFrame in the
application or applet.
Example:
SubFrame subFrame = new
SubFrame("SubFrame Title");
Liang,Introduction to Java Programming,revised by Dai-kaiyu
55
Creating Additional Windows, Step 3
Step 3: Create a JButton for activating the
subFrame.
add(new JButton("Activate SubFrame"));
Liang,Introduction to Java Programming,revised by Dai-kaiyu
56
Creating Additional Windows, Step 4
Step 4: Override the actionPerformed()
method as follows:
public actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (e.target instanceof Button) {
if ("Activate SubFrame".equals(actionCommand)) {
subFrame.setVisible(true);
}
}
}
Liang,Introduction to Java Programming,revised by Dai-kaiyu
57
Example 13.10 Creating Multiple
Windows
This example 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
occurrence of the letters in the text area.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
58
Example 13.10, cont.
MultipleWindowsDemo
Run
Histogram
Liang,Introduction to Java Programming,revised by Dai-kaiyu
59
Using Menus with Frames
Menus
Allows for performing actions with cluttering GUI
Contained by menu bar
JMenuBar
Comprised of menu items
JMenuItem
Liang,Introduction to Java Programming,revised by Dai-kaiyu
60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Fig. 13.10: MenuTest.java
// Demonstrating menus
// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class MenuTest extends JFrame {
private Color colorValues[] =
{ Color.black, Color.blue, Color.red, Color.green };
private JRadioButtonMenuItem colorItems[], fonts[];
private JCheckBoxMenuItem styleItems[];
private JLabel displayLabel;
private ButtonGroup fontGroup, colorGroup;
private int style;
// set up GUI
public MenuTest()
{
super( "Using JMenus" );
// set up File menu and its menu items
JMenu fileMenu = new JMenu( "File" );
fileMenu.setMnemonic( 'F' );
Instantiate File JMenu
// set up About... menu item
JMenuItem aboutItem = new JMenuItem( "About..." );
aboutItem.setMnemonic( 'A' );
Instantiate About… JMenuItem
aboutItem.addActionListener( Liang,Introduction to Java Programming,revised by Dai-kaiyu
to be placed in fileMenu
61
36
// anonymous inner class to handle menu item event
37
new ActionListener() {
38
39
// display message dialog when user selects About...
40
public void actionPerformed( ActionEvent event )
41
{
Modal Dialog
42
JOptionPane.showMessageDialog( MenuTest.this,
43
"This is an example\nof using menus",
44
"About", JOptionPane.PLAIN_MESSAGE );
45
}
When user selects About…
46
Refer to
47
} // end anonymous inner class
JMenuItem, display message
48
MenuTest
dialog with appropriate text
49
); // end call to addActionListener
50
51
fileMenu.add( aboutItem );
52
53
// set up Exit menu item
Instantiate Exit JMenuItem
54
JMenuItem exitItem = new JMenuItem( "Exit" );
55
exitItem.setMnemonic( 'x' );
to be placed in fileMenu
56
57
exitItem.addActionListener(
58
59
// anonymous inner class to handle exitItem event
60
new ActionListener() {
61
62
// terminate application when user clicks exitItem
63
public void actionPerformed( ActionEvent event )
64
{
65
System.exit( 0 );
When user selects Exit
66
}
67
JMenuItem, exit system
68
} // end anonymous inner class
69
Liang,Introduction to Java Programming,revised by Dai-kaiyu
62
70
); // end call to addActionListener
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
fileMenu.add( exitItem );
// create menu bar and attach it to MenuTest window
JMenuBar bar = new JMenuBar();
setJMenuBar( bar );
bar.add( fileMenu );
// create Format menu, its submenus and menu items
JMenu formatMenu = new JMenu( "Format" );
formatMenu.setMnemonic( 'r' );
Instantiate JMenuBar
to contain JMenus
Instantiate Format JMenu
// create Color submenu
String colors[] = { "Black", "Blue", "Red", "Green" };
JMenu colorMenu = new JMenu( "Color" );
colorMenu.setMnemonic( 'C' );
Instantiate Color JMenu
(submenu of Format JMenu)
colorItems = new JRadioButtonMenuItem[ colors.length ];
colorGroup = new ButtonGroup();
ItemHandler itemHandler = new ItemHandler();
// create color radio button menu items
for ( int count = 0; count < colors.length; count++ ) {
colorItems[ count ] =
new JRadioButtonMenuItem( colors[ count ] );
colorMenu.add( colorItems[ count ] );
colorGroup.add( colorItems[ count ] );
Instantiate
JRadioButtonMenuItems for
Color JMenu and ensure that only
one menu item is selected at a time
colorItems[ count ].addActionListener( itemHandler );
}
// select first Color menu item Liang,Introduction to Java Programming,revised by Dai-kaiyu
colorItems[ 0 ].setSelected( true );
63
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// add format menu to menu bar
formatMenu.add( colorMenu );
formatMenu.addSeparator();
Separator places line
between JMenuItems
// create Font submenu
String fontNames[] = { "Serif", "Monospaced", "SansSerif" };
JMenu fontMenu = new JMenu( "Font" );
fontMenu.setMnemonic( 'n' );
Instantiate Font JMenu
(submenu of Format JMenu)
fonts = new JRadioButtonMenuItem[ fontNames.length ];
fontGroup = new ButtonGroup();
// create Font radio button menu items
for ( int count = 0; count < fonts.length; count++ ) {
fonts[ count ] =
new JRadioButtonMenuItem( fontNames[ count ] );
fontMenu.add( fonts[ count ] );
fontGroup.add( fonts[ count ] );
fonts[ count ].addActionListener( itemHandler );
}
Instantiate
JRadioButtonMenuItems for
Font JMenu and ensure that only
one menu item is selected at a time
// select first Font menu item
fonts[ 0 ].setSelected( true );
fontMenu.addSeparator();
// set up style menu items
String styleNames[] = { "Bold", "Italic" };
Liang,Introduction
to Java Programming,revised
by Dai-kaiyu
styleItems = new JCheckBoxMenuItem[
styleNames.length
];
StyleHandler styleHandler = new StyleHandler();
64
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// create style checkbox menu items
for ( int count = 0; count < styleNames.length; count++ ) {
styleItems[ count ] =
new JCheckBoxMenuItem( styleNames[ count ] );
fontMenu.add( styleItems[ count ] );
styleItems[ count ].addItemListener( styleHandler );
}
// put Font menu in Format menu
formatMenu.add( fontMenu );
// add Format menu to menu bar
bar.add( formatMenu );
// set up label to display text
displayLabel = new JLabel(
"Sample Text", SwingConstants.CENTER );
displayLabel.setForeground( colorValues[ 0 ] );
displayLabel.setFont(
new Font( "TimesRoman", Font.PLAIN, 72 ) );
getContentPane().setBackground( Color.cyan );
getContentPane().add( displayLabel, BorderLayout.CENTER );
setSize( 500, 200 );
setVisible( true );
} // end constructor
Liang,Introduction to Java Programming,revised by Dai-kaiyu
65
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// execute application
public static void main( String args[] )
{
MenuTest application = new MenuTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
Invoked when user selects JMenuItem
// inner class to handle action events from menu items
private class ItemHandler implements ActionListener {
// process color and font selections
public void actionPerformed( ActionEvent event )
{
// process color selection
for ( int count = 0; count < colorItems.length; count++ )
if ( colorItems[ count ].isSelected() ) {
displayLabel.setForeground( colorValues[ count ] );
break;
}
// process font selection
for ( int count = 0; count < fonts.length; count++ )
Determine which font or color
menu generated event
Set font or color of JLabel,
respectively
if ( event.getSource() == fonts[ count ] ) {
displayLabel.setFont( new Font(
fonts[ count ].getText(), style, 72 ) );
break;
}
repaint();
}
Liang,Introduction to Java Programming,revised by Dai-kaiyu
66
208
} // end class ItemHandler
209
210
// inner class to handle item events from check box menu items
211 private class StyleHandler implements ItemListener {
212
213
// process font style selections
214
public void itemStateChanged( ItemEvent e )
215
{
216
style = 0;
217
218
// check for bold selection
219
if ( styleItems[ 0 ].isSelected() )
220
style += Font.BOLD;
221
222
// check for italic selection
223
if ( styleItems[ 1 ].isSelected() )
224
style += Font.ITALIC;
225
226
displayLabel.setFont( new Font(
227
displayLabel.getFont().getName(), style, 72 ) );
228
229
repaint();
230
}
231
232
} // end class StyleHandler
233
234 } // end class MenuTest
Invoked when user selects
JCheckBoxMenuItem
Determine new font style
Liang,Introduction to Java Programming,revised by Dai-kaiyu
67
MenuTest.java
Program Output
Liang,Introduction to Java Programming,revised by Dai-kaiyu
68