Java Reference
In-Depth Information
Thumb
Tick mark
Fig. 22.1
|
JSlider
component with horizontal orientation.
Most Swing GUI components support mouse and keyboard interactions—e.g., if a
JSlider
has the focus (i.e., it's the currently selected GUI component in the user inter-
face), pressing the left arrow key or right arrow key causes the
JSlider
's thumb to decrease
or increase by 1, respectively. The down arrow key and up arrow key also cause the thumb
to decrease or increase by 1 tick, respectively. The
PgDn
(page down)
key
and
PgUp
(page
up)
key
cause the thumb to decrease or increase by
block increments
of one-tenth of the
range of values, respectively. The
Home
key
moves the thumb to the minimum value of the
JSlider
, and the
End key
moves the thumb to the maximum value of the
JSlider
.
JSlider
s have either a horizontal or a vertical orientation. For a horizontal
JSlider
,
the minimum value is at the left end
and the maximum is at the right end. For a vertical
JSlider
, the minimum value is at the bottom and the maximum is at the top. The min-
imum and maximum value positions on a
JSlider
can be reversed by invoking
JSlider
method
setInverted
with
boolean
argument
true
. The relative position of the thumb
indicates the current value of the
JSlider
.
The program in Figs. 22.2-22.4 allows the user to size a circle drawn on a subclass of
JPanel
called
OvalPanel
(Fig. 22.2). The user specifies the circle's diameter with a hori-
zontal
JSlider
. Class
OvalPanel
knows how to draw a circle on itself, using its own
instance variable
diameter
to determine the diameter of the circle—the
diameter
is used
as the width and height of the bounding box in which the circle is displayed. The
diameter
value is set when the user interacts with the
JSlider
. The event handler calls method
set-
Diameter
in class
OvalPanel
to set the
diameter
and calls
repaint
to draw the new circle.
The
repaint
call results in a call to
OvalPanel
's
paintComponent
method.
1
// Fig. 22.2: OvalPanel.java
2
// A customized JPanel class.
3
import
java.awt.Graphics;
4
import
java.awt.Dimension;
5
import
javax.swing.JPanel;
6
7
public
class
OvalPanel
extends
JPanel
8
{
9
private
int
diameter =
10
;
// default diameter
10
11
// draw an oval of the specified diameter
12
@Override
13
public
void
paintComponent(Graphics g)
14
{
15
super
.paintComponent(g);
16
g.fillOval(
10
,
10
, diameter, diameter);
17
}
18
Fig. 22.2
|
JPanel
subclass for drawing circles of a specified diameter. (Part 1 of 2.)