Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Intro_Java_brief_Liang2011.pdf
Скачиваний:
195
Добавлен:
26.03.2016
Размер:
10.44 Mб
Скачать

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}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]