- •CONTENTS
- •1.1 Introduction
- •1.2 What Is a Computer?
- •1.3 Programs
- •1.4 Operating Systems
- •1.5 Java, World Wide Web, and Beyond
- •1.6 The Java Language Specification, API, JDK, and IDE
- •1.7 A Simple Java Program
- •1.8 Creating, Compiling, and Executing a Java Program
- •1.9 (GUI) Displaying Text in a Message Dialog Box
- •2.1 Introduction
- •2.2 Writing Simple Programs
- •2.3 Reading Input from the Console
- •2.4 Identifiers
- •2.5 Variables
- •2.7 Named Constants
- •2.8 Numeric Data Types and Operations
- •2.9 Problem: Displaying the Current Time
- •2.10 Shorthand Operators
- •2.11 Numeric Type Conversions
- •2.12 Problem: Computing Loan Payments
- •2.13 Character Data Type and Operations
- •2.14 Problem: Counting Monetary Units
- •2.15 The String Type
- •2.16 Programming Style and Documentation
- •2.17 Programming Errors
- •2.18 (GUI) Getting Input from Input Dialogs
- •3.1 Introduction
- •3.2 boolean Data Type
- •3.3 Problem: A Simple Math Learning Tool
- •3.4 if Statements
- •3.5 Problem: Guessing Birthdays
- •3.6 Two-Way if Statements
- •3.7 Nested if Statements
- •3.8 Common Errors in Selection Statements
- •3.9 Problem: An Improved Math Learning Tool
- •3.10 Problem: Computing Body Mass Index
- •3.11 Problem: Computing Taxes
- •3.12 Logical Operators
- •3.13 Problem: Determining Leap Year
- •3.14 Problem: Lottery
- •3.15 switch Statements
- •3.16 Conditional Expressions
- •3.17 Formatting Console Output
- •3.18 Operator Precedence and Associativity
- •3.19 (GUI) Confirmation Dialogs
- •4.1 Introduction
- •4.2 The while Loop
- •4.3 The do-while Loop
- •4.4 The for Loop
- •4.5 Which Loop to Use?
- •4.6 Nested Loops
- •4.7 Minimizing Numeric Errors
- •4.8 Case Studies
- •4.9 Keywords break and continue
- •4.10 (GUI) Controlling a Loop with a Confirmation Dialog
- •5.1 Introduction
- •5.2 Defining a Method
- •5.3 Calling a Method
- •5.4 void Method Example
- •5.5 Passing Parameters by Values
- •5.6 Modularizing Code
- •5.7 Problem: Converting Decimals to Hexadecimals
- •5.8 Overloading Methods
- •5.9 The Scope of Variables
- •5.10 The Math Class
- •5.11 Case Study: Generating Random Characters
- •5.12 Method Abstraction and Stepwise Refinement
- •6.1 Introduction
- •6.2 Array Basics
- •6.3 Problem: Lotto Numbers
- •6.4 Problem: Deck of Cards
- •6.5 Copying Arrays
- •6.6 Passing Arrays to Methods
- •6.7 Returning an Array from a Method
- •6.8 Variable-Length Argument Lists
- •6.9 Searching Arrays
- •6.10 Sorting Arrays
- •6.11 The Arrays Class
- •7.1 Introduction
- •7.2 Two-Dimensional Array Basics
- •7.3 Processing Two-Dimensional Arrays
- •7.4 Passing Two-Dimensional Arrays to Methods
- •7.5 Problem: Grading a Multiple-Choice Test
- •7.6 Problem: Finding a Closest Pair
- •7.7 Problem: Sudoku
- •7.8 Multidimensional Arrays
- •8.1 Introduction
- •8.2 Defining Classes for Objects
- •8.3 Example: Defining Classes and Creating Objects
- •8.4 Constructing Objects Using Constructors
- •8.5 Accessing Objects via Reference Variables
- •8.6 Using Classes from the Java Library
- •8.7 Static Variables, Constants, and Methods
- •8.8 Visibility Modifiers
- •8.9 Data Field Encapsulation
- •8.10 Passing Objects to Methods
- •8.11 Array of Objects
- •9.1 Introduction
- •9.2 The String Class
- •9.3 The Character Class
- •9.4 The StringBuilder/StringBuffer Class
- •9.5 Command-Line Arguments
- •9.6 The File Class
- •9.7 File Input and Output
- •9.8 (GUI) File Dialogs
- •10.1 Introduction
- •10.2 Immutable Objects and Classes
- •10.3 The Scope of Variables
- •10.4 The this Reference
- •10.5 Class Abstraction and Encapsulation
- •10.6 Object-Oriented Thinking
- •10.7 Object Composition
- •10.8 Designing the Course Class
- •10.9 Designing a Class for Stacks
- •10.10 Designing the GuessDate Class
- •10.11 Class Design Guidelines
- •11.1 Introduction
- •11.2 Superclasses and Subclasses
- •11.3 Using the super Keyword
- •11.4 Overriding Methods
- •11.5 Overriding vs. Overloading
- •11.6 The Object Class and Its toString() Method
- •11.7 Polymorphism
- •11.8 Dynamic Binding
- •11.9 Casting Objects and the instanceof Operator
- •11.11 The ArrayList Class
- •11.12 A Custom Stack Class
- •11.13 The protected Data and Methods
- •11.14 Preventing Extending and Overriding
- •12.1 Introduction
- •12.2 Swing vs. AWT
- •12.3 The Java GUI API
- •12.4 Frames
- •12.5 Layout Managers
- •12.6 Using Panels as Subcontainers
- •12.7 The Color Class
- •12.8 The Font Class
- •12.9 Common Features of Swing GUI Components
- •12.10 Image Icons
- •13.1 Introduction
- •13.2 Exception-Handling Overview
- •13.3 Exception-Handling Advantages
- •13.4 Exception Types
- •13.5 More on Exception Handling
- •13.6 The finally Clause
- •13.7 When to Use Exceptions
- •13.8 Rethrowing Exceptions
- •13.9 Chained Exceptions
- •13.10 Creating Custom Exception Classes
- •14.1 Introduction
- •14.2 Abstract Classes
- •14.3 Example: Calendar and GregorianCalendar
- •14.4 Interfaces
- •14.5 Example: The Comparable Interface
- •14.6 Example: The ActionListener Interface
- •14.7 Example: The Cloneable Interface
- •14.8 Interfaces vs. Abstract Classes
- •14.9 Processing Primitive Data Type Values as Objects
- •14.10 Sorting an Array of Objects
- •14.11 Automatic Conversion between Primitive Types and Wrapper Class Types
- •14.12 The BigInteger and BigDecimal Classes
- •14.13 Case Study: The Rational Class
- •15.1 Introduction
- •15.2 Graphical Coordinate Systems
- •15.3 The Graphics Class
- •15.4 Drawing Strings, Lines, Rectangles, and Ovals
- •15.5 Case Study: The FigurePanel Class
- •15.6 Drawing Arcs
- •15.7 Drawing Polygons and Polylines
- •15.8 Centering a String Using the FontMetrics Class
- •15.9 Case Study: The MessagePanel Class
- •15.10 Case Study: The StillClock Class
- •15.11 Displaying Images
- •15.12 Case Study: The ImageViewer Class
- •16.1 Introduction
- •16.2 Event and Event Source
- •16.3 Listeners, Registrations, and Handling Events
- •16.4 Inner Classes
- •16.5 Anonymous Class Listeners
- •16.6 Alternative Ways of Defining Listener Classes
- •16.7 Problem: Loan Calculator
- •16.8 Window Events
- •16.9 Listener Interface Adapters
- •16.10 Mouse Events
- •16.11 Key Events
- •16.12 Animation Using the Timer Class
- •17.1 Introduction
- •17.2 Buttons
- •17.3 Check Boxes
- •17.4 Radio Buttons
- •17.5 Labels
- •17.6 Text Fields
- •17.7 Text Areas
- •17.8 Combo Boxes
- •17.9 Lists
- •17.10 Scroll Bars
- •17.11 Sliders
- •17.12 Creating Multiple Windows
- •18.1 Introduction
- •18.2 Developing Applets
- •18.3 The HTML File and the <applet> Tag
- •18.4 Applet Security Restrictions
- •18.5 Enabling Applets to Run as Applications
- •18.6 Applet Life-Cycle Methods
- •18.7 Passing Strings to Applets
- •18.8 Case Study: Bouncing Ball
- •18.9 Case Study: TicTacToe
- •18.10 Locating Resources Using the URL Class
- •18.11 Playing Audio in Any Java Program
- •18.12 Case Study: Multimedia Animations
- •19.1 Introduction
- •19.2 How is I/O Handled in Java?
- •19.3 Text I/O vs. Binary I/O
- •19.4 Binary I/O Classes
- •19.5 Problem: Copying Files
- •19.6 Object I/O
- •19.7 Random-Access Files
- •20.1 Introduction
- •20.2 Problem: Computing Factorials
- •20.3 Problem: Computing Fibonacci Numbers
- •20.4 Problem Solving Using Recursion
- •20.5 Recursive Helper Methods
- •20.6 Problem: Finding the Directory Size
- •20.7 Problem: Towers of Hanoi
- •20.8 Problem: Fractals
- •20.9 Problem: Eight Queens
- •20.10 Recursion vs. Iteration
- •20.11 Tail Recursion
- •APPENDIXES
- •INDEX
596 Chapter 17 Creating Graphical User Interfaces
70jlblImageViewer[i].setIcon(null);
71}
72}
73});
74}
75}
The anonymous inner-class listener listens to ListSelectionEvent for handling the selection of country names in the list (lines 56–73). ListSelectionEvent and ListSelectionListener are defined in the javax.swing.event package, so this package is imported in the program (line 3).
The program creates an array of nine labels for displaying flag images for nine countries. The program loads the images of the nine countries into an image array (lines 17–27) and creates a list of the nine countries in the same order as in the image array (lines 9–11). Thus the index 0 of the image array corresponds to the first country in the list.
The list is placed in a scroll pane (line 53) so that it can be scrolled when the number of items in the list extends beyond the viewing area.
By default, the selection mode of the list is multiple-interval, which allows the user to select multiple items from different blocks in the list. When the user selects countries in the list, the valueChanged handler (lines 58–73) is executed, which gets the indices of the selected item and sets their corresponding image icons in the label to display the flags.
17.10 Scroll Bars
JScrollBar is a component that enables the user to select from a range of values, as shown in Figure 17.26.
Minimum value |
Maximum value |
Block decrement |
Block increment |
|
Bubble |
Unit decrement |
Unit increment |
FIGURE 17.26 A scroll bar represents a range of values graphically.
Normally, the user changes the value of the scroll bar by making a gesture with the mouse. For example, the user can drag the scroll bar’s bubble up and down, or click in the scroll bar’s unit-increment or block-increment areas. Keyboard gestures can also be mapped to the scroll bar. By convention, the Page Up and Page Down keys are equivalent to clicking in the scroll bar’s block-increment and block-decrement areas.
Note
The width of the scroll bar’s track corresponds to maximum + visibleAmount. When a scroll bar is set to its maximum value, the left side of the bubble is at maximum, and the right side is at maximum + visibleAmount.
JScrollBar has the following properties, as shown in Figure 17.27.
When the user changes the value of the scroll bar, the scroll bar fires an instance of AdjustmentEvent, which is passed to every registered listener. An object that wishes to be notified of changes to the scroll bar’s value must implement the adjustmentValueChanged method in the java.awt.event.AdjustmentListener interface.
17.10 Scroll Bars 597
javax.swing.JComponent
The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.
javax.swing.JScrollBar
-orientation: int -maximum: int
-minimum: int
-visibleAmount: int
-value: int -blockIncrement: int
-unitIncrement: int
+JScrollBar() +JScrollBar(orientation: int)
+JScrollBar(orientation: int, value: int, extent: int, min: int, max: int)
+addAdjustmentListener(listener: AdjustmentListener): void
FIGURE 17.27 JScrollBar enables you to select from a range of values.
Listing 17.10 gives a program that uses horizontal and vertical scroll bars to control a message displayed on a panel. The horizontal scroll bar is used to move the message to the left or the right, and the vertical scroll bar to move it up and down. A sample run of the program is shown in Figure 17.28.
Message panel |
Vertical scroll bar |
|
Horizontal scroll bar
FIGURE 17.28 The scroll bars move the message on a panel horizontally and vertically.
Here are the major steps in the program:
1.Create the user interface.
Create a MessagePanel object and place it in the center of the frame. Create a vertical scroll bar and place it in the east of the frame. Create a horizontal scroll bar and place it in the south of the frame.
2.Process the event.
Create listeners to implement the adjustmentValueChanged handler to move the message according to the bar movement in the scroll bars.
598 Chapter 17 |
Creating Graphical User Interfaces |
||||||
|
LISTING 17.10 ScrollBarDemo.java |
||||||
|
1 |
import java.awt.*; |
|||||
|
2 |
import java.awt.event.*; |
|||||
|
3 |
import javax.swing.*; |
|||||
|
4 |
|
|
|
|
|
|
|
5 |
public class ScrollBarDemo extends JFrame { |
|||||
|
6 |
// Create horizontal and vertical scroll bars |
|||||
horizontal scroll bar |
7 |
private JScrollBar jscbHort = |
|||||
|
8 |
|
new JScrollBar(JScrollBar.HORIZONTAL); |
|
|||
vertical scroll bar |
9 |
private JScrollBar jscbVert = |
|||||
|
10 |
|
new JScrollBar(JScrollBar.VERTICAL); |
|
|
||
|
11 |
|
|
|
|
|
|
|
12 |
// Create a MessagePanel |
|||||
|
13 |
private MessagePanel messagePanel = |
|||||
|
14 |
|
new MessagePanel("Welcome to Java"); |
||||
|
15 |
|
|
|
|
|
|
|
16 |
public static void main(String[] args) { |
|||||
create frame |
17 |
|
ScrollBarDemo frame = new ScrollBarDemo(); |
||||
|
18 |
|
frame.setTitle("ScrollBarDemo"); |
||||
|
19 |
|
frame.setLocationRelativeTo(null); // Center the frame |
||||
|
20 |
|
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
||||
|
21 |
|
frame.pack(); |
||||
|
22 |
|
frame.setVisible(true); |
||||
|
23 |
} |
|
|
|
|
|
|
24 |
|
|
|
|
|
|
|
25 |
public ScrollBarDemo() { |
|||||
|
26 |
|
// Add scroll bars and message panel to the frame |
||||
create UI |
27 |
|
setLayout(new BorderLayout()); |
||||
|
28 |
|
add(messagePanel, BorderLayout.CENTER); |
||||
add scroll bar |
29 |
|
add(jscbVert, BorderLayout.EAST); |
||||
|
30 |
|
add(jscbHort, BorderLayout.SOUTH); |
||||
|
31 |
|
|
|
|
|
|
|
32 |
|
// Register listener for the scroll bars |
||||
adjustment listener |
33 |
|
jscbHort.addAdjustmentListener(new AdjustmentListener() { |
|
|||
|
34 |
|
public void adjustmentValueChanged(AdjustmentEvent e) { |
||||
|
35 |
|
// getValue() and getMaximumValue() return int, but for better |
||||
|
36 |
|
// precision, use double |
||||
|
37 |
|
double value = jscbHort.getValue(); |
||||
|
38 |
|
double maximumValue = jscbHort.getMaximum(); |
||||
|
39 |
|
double newX = (value * messagePanel.getWidth() / |
||||
|
40 |
|
maximumValue); |
||||
|
41 |
|
messagePanel.setXCoordinate((int)newX); |
||||
|
42 |
} |
|
|
|
|
|
|
43 |
}); |
|
|
|
|
|
adjustment listener |
44 |
|
jscbVert.addAdjustmentListener(new AdjustmentListener() { |
|
|||
|
45 |
|
public void adjustmentValueChanged(AdjustmentEvent e) { |
||||
|
46 |
|
// getValue() and getMaximumValue() return int, but for better |
||||
|
47 |
|
// precision, use double |
||||
|
48 |
|
double value = jscbVert.getValue(); |
||||
|
49 |
|
double maximumValue = jscbVert.getMaximum(); |
||||
|
50 |
|
double newY = (value * messagePanel.getHeight() / |
||||
|
51 |
|
maximumValue); |
||||
|
52 |
|
messagePanel.setYCoordinate((int)newY); |
||||
|
53 |
} |
|
|
|
|
|
|
54 |
}); |
|
|
|
|
|
|
55 |
} |
|
|
|
|
|
|
56 |
} |
|
|
|
|
|
17.11 Sliders 599
The program creates two scroll bars (jscbVert and jscbHort) (lines 7–10) and an instance of MessagePanel (messagePanel) (lines 13–14). messagePanel is placed in the center of the frame; jscbVert and jscbHort are placed in the east and south sections of the frame (lines 29–30), respectively.
You can specify the orientation of the scroll bar in the constructor or use the setOrientation method. By default, the property value is 100 for maximum, 0 for minimum, 10 for blockIncrement, and 10 for visibleAmount.
When the user drags the bubble, or clicks the increment or decrement unit, the value of the scroll bar changes. An instance of AdjustmentEvent is fired and passed to the listener by invoking the adjustmentValueChanged handler. The listener for the vertical scroll bar moves the message up and down (lines 33–43), and the listener for the horizontal bar moves 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 between the x value and the width of the message panel. Similarly, the ratio between the 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 response to the scroll bar adjustments (lines 39, 50).
17.11 Sliders
JSlider is similar to JScrollBar, but JSlider has more properties and can appear in many forms. Figure 17.29 shows two sliders.
MessagePanel |
Vertical slider |
|
|
|
Horizontal slider |
FIGURE 17.29 The sliders move the message on a panel horizontally and vertically.
JSlider lets the user graphically select a value by sliding a knob within a bounded interval. The slider can show both major tick marks and minor tick marks between them. The number of pixels between the tick marks is controlled by the majorTickSpacing and minorTickSpacing properties. Sliders can be displayed horizontally or vertically, with or without ticks, and with or without labels. The frequently used constructors and properties in JSlider are shown in Figure 17.30.
Note
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.
Note
All the properties listed in Figure 17.30 have the associated get and set methods, which are omitted for brevity. By convention, the get method for a Boolean property is named is<PropertyName>(). In the JSlider class, the get methods for paintLabels, paintTicks, paintTrack, and inverted are getPaintLabels(), getPaintTicks(), getPaintTrack(), and getInverted(), which violate the naming convention.
600 Chapter 17 Creating Graphical User Interfaces
javax.swing.JComponent
javax.swing.JSlider
-maximum: int -minimum: int -value: int -orientation: int
-paintLabels: boolean -paintTicks: boolean -paintTrack: boolean -majorTickSpacing: int -minorTickSpacing: int -inverted: boolean
+JSlider()
+JSlider(min: int, max: int) +JSlider(min: int, max: int, value: int) +JSlider(orientation: int)
+JSlider(orientation: int, min: int, max: int, value: int)
+addChangeListener(listener: ChangeListener) :void
The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.
FIGURE 17.30 JSlider enables you to select from a range of values.
When the user changes the value of the slider, the slider fires an instance of javax.swing.event.ChangeEvent, which is passed to any registered listeners. Any object that wishes to be notified of changes to the slider’s value must implement the stateChanged method in the ChangeListener interface defined in the package javax.swing.event.
Listing 17.11 writes a program that uses the sliders to control a message displayed on a panel, as shown in Figure 17.29. Here are the major steps in the program:
1.Create the user interface.
Create a MessagePanel object and place it in the center of the frame. Create a vertical slider and place it in the east of the frame. Create a horizontal slider and place it in the south of the frame.
2.Process the event.
Create listeners to implement the stateChanged handler in the ChangeListener interface to move the message according to the knot movement in the slider.
LISTING 17.11 SliderDemo.java
1 import java.awt.*;
2 import javax.swing.*;
3 import javax.swing.event.*;
4
5 public class SliderDemo extends JFrame {
|
6 |
// Create horizontal and |
vertical sliders |
|
horizontal slider |
7 |
private JSlider |
jsldHort |
= new JSlider(JSlider.HORIZONTAL); |
vertical slider |
8 |
private JSlider |
jsldVert = new JSlider(JSlider.VERTICAL); |
|
|
9 |
|
|
|
17.11 Sliders 601
10// Create a MessagePanel
11private MessagePanel messagePanel =
12new MessagePanel("Welcome to Java");
14public static void main(String[] args) {
15 |
SliderDemo frame = new SliderDemo(); |
create frame |
16frame.setTitle("SliderDemo");
17frame.setLocationRelativeTo(null); // Center the frame
18frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19frame.pack();
20frame.setVisible(true);
21}
22 |
|
|
23 |
public SliderDemo() { |
create UI |
24// Add sliders and message panel to the frame
25setLayout(new BorderLayout(5, 5));
26add(messagePanel, BorderLayout.CENTER);
27add(jsldVert, BorderLayout.EAST);
28add(jsldHort, BorderLayout.SOUTH);
29 |
|
|
30 |
// Set properties for sliders |
|
31 |
jsldHort.setMaximum(50); |
slider properties |
32jsldHort.setPaintLabels(true);
33jsldHort.setPaintTicks(true);
34jsldHort.setMajorTickSpacing(10);
35jsldHort.setMinorTickSpacing(1);
36jsldHort.setPaintTrack(false);
37jsldVert.setInverted(true);
38jsldVert.setMaximum(10);
39jsldVert.setPaintLabels(true);
40jsldVert.setPaintTicks(true);
41jsldVert.setMajorTickSpacing(10);
42jsldVert.setMinorTickSpacing(1);
44// Register listener for the sliders
45 |
jsldHort.addChangeListener(new ChangeListener() { |
listener |
46/** Handle scroll-bar adjustment actions */
47public void stateChanged(ChangeEvent e) {
48// getValue() and getMaximumValue() return int, but for better
49// precision, use double
50double value = jsldHort.getValue();
51double maximumValue = jsldHort.getMaximum();
52double newX = (value * messagePanel.getWidth() /
53maximumValue);
54messagePanel.setXCoordinate((int)newX);
55}
56});
57 |
jsldVert.addChangeListener(new ChangeListener() { |
listener |
58/** Handle scroll-bar adjustment actions */
59public void stateChanged(ChangeEvent e) {
60// getValue() and getMaximumValue() return int, but for better
61// precision, use double
62double value = jsldVert.getValue();
63double maximumValue = jsldVert.getMaximum();
64double newY = (value * messagePanel.getHeight() /
65maximumValue);
66messagePanel.setYCoordinate((int) newY);
67}
68});
69}
70}