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

602 Chapter 17 Creating Graphical User Interfaces

JSlider is similar to JScrollBar but has more features. As shown in this example, you can specify maximum, labels, major ticks, and minor ticks on a JSlider (lines 31–35). You can also choose to hide the track (line 36). Since the values of a vertical slider decrease from top to bottom, the setInverted method reverses the order (line 37).

JSlider fires ChangeEvent when the slider is changed. The listener needs to implement the stateChanged handler in ChangeListener (lines 45–68). Note that JScrollBar fires AdjustmentEvent when the scroll bar is adjusted.

17.12 Creating Multiple Windows

Occasionally, you may want to create multiple windows in an application. The application opens a new window to perform a specified task. The new windows are called subwindows, 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 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.

FIGURE 17.31 The histogram is displayed in a separate frame.

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. 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 count to the Histogram object.

b.Create a new frame and place the Histogram object in the center of frame. Display the frame.

17.12 Creating Multiple Windows 603

LISTING 17.12 MultipleWindowsDemo.java

1 import java.awt.*;

2 import java.awt.event.*;

3 import javax.swing.*;

4

5 public class MultipleWindowsDemo extends JFrame {

6private JTextArea jta;

7

private JButton jbtShowHistogram = new JButton("Show Histogram");

 

8

 

private Histogram histogram = new Histogram();

 

 

9

 

 

 

 

 

10

// Create a new frame to hold the histogram panel

 

11

 

private JFrame histogramFrame = new JFrame();

 

 

create subframe

12

 

 

 

 

 

13

public MultipleWindowsDemo() {

create UI

14// Store text area in a scroll pane

15JScrollPane scrollPane = new JScrollPane(jta = new JTextArea());

16scrollPane.setPreferredSize(new Dimension(300, 200));

17jta.setWrapStyleWord(true);

18jta.setLineWrap(true);

19

20// Place scroll pane and button in the frame

21add(scrollPane, BorderLayout.CENTER);

22add(jbtShowHistogram, BorderLayout.SOUTH);

24// Register listener

25jbtShowHistogram.addActionListener(new ActionListener() {

26/** Handle the button action */

27public void actionPerformed(ActionEvent e) {

28// Count the letters in the text area

29int[] count = countLetters();

30

31// Set the letter count to histogram for display

32histogram.showHistogram(count);

33

 

 

34

// Show the frame

 

35

histogramFrame.setVisible(true);

display subframe

36}

37});

39// Create a new frame to hold the histogram panel

40histogramFrame.add(histogram);

41histogramFrame.pack();

42histogramFrame.setTitle("Histogram");

43}

44

45/** Count the letters in the text area */

46private int[] countLetters() {

47// Count for 26 letters

48int[] count = new int[26];

49

50// Get contents from the text area

51String text = jta.getText();

52

53// Count occurrences of each letter (case insensitive)

54for (int i = 0; i < text.length(); i++) {

55char character = text.charAt(i);

56

604 Chapter 17

Creating Graphical User Interfaces

 

57

if ((character >= 'A') && (character <= 'Z')) {

 

58

count[character - 'A']++;

 

59

}

 

60

else if ((character >= 'a') && (character <= 'z')) {

 

61

count[character - 'a']++;

 

62

}

 

63

}

 

64

 

 

65

return count; // Return the count array

 

66

}

 

67

 

 

68

public static void main(String[] args) {

create main frame

69

MultipleWindowsDemo frame = new MultipleWindowsDemo();

 

70

frame.setLocationRelativeTo(null); // Center the frame

 

71

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

72

frame.setTitle("MultipleWindowsDemo");

 

73

frame.pack();

 

74

frame.setVisible(true);

 

75

}

 

76

}

LISTING 17.13 Histogram.java

1 import javax.swing.*;

2 import java.awt.*;

3

4 public class Histogram extends JPanel {

5 // Count the occurrences of 26 letters

6 private int[] count;

7

8 /** Set the count and display histogram */

9 public void showHistogram(int[] count) {

 

10

this.count = count;

 

11

repaint();

 

12

}

 

13

 

 

14

/** Paint the histogram */

paint histogram

15

protected void paintComponent(Graphics g) {

 

16

if (count == null) return; // No display if count is null

 

17

 

 

18

super.paintComponent(g);

 

19

 

 

20

// Find the panel size and bar width and interval dynamically

 

21

int width = getWidth();

 

22

int height = getHeight();

 

23

int interval = (width - 40) / count.length;

 

24

int individualWidth = (int)(((width - 40) / 24) * 0.60);

 

25

 

 

26

// Find the maximum count. The maximum count has the highest bar

 

27

int maxCount = 0;

 

28

for (int i = 0; i < count.length; i++) {

 

29

if (maxCount < count[i])

 

30

maxCount = count[i];

 

31

}

 

32

 

 

33

// x is the start position for the first bar in the histogram

 

34

int x = 30;

 

35

 

 

36

// Draw a horizontal base line

17.12 Creating Multiple Windows 605

37g.drawLine(10, height - 45, width - 10, height - 45);

38for (int i = 0; i < count.length; i++) {

39// Find the bar height

40int barHeight =

41(int)(((double)count[i] / (double)maxCount) * (height - 55));

43// Display a bar (i.e. rectangle)

44g.drawRect(x, height - 45 - barHeight, individualWidth,

45

barHeight);

46

 

47// Display a letter under the base line

48g.drawString((char)(65 + i) + "", x, height - 30);

50// Move x for displaying the next character

51x += interval;

52}

53}

55/** Override getPreferredSize */

56

public Dimension getPreferredSize() {

preferredSize

57

return new Dimension(300, 300);

 

58

}

 

59

}

 

The program contains two classes: MultipleWindowsDemo and Histogram. Their relationship is shown in Figure 17.32.

 

javax.swing.JPanel

 

 

 

 

javax.swing.JFrame

 

 

1

1

 

 

 

 

Histogram

 

MultipleWindowsDemo

 

 

 

 

-count: int[]

 

 

-jta: JTextArea

+showHistogram(count: int[]): void

 

 

-histogram: Histogram

 

 

-jbtShowHistogram: JButton

#paintComponent(g: Graphics): void

 

 

 

 

-countLetters(): int[]

 

 

 

 

 

 

 

 

 

 

 

 

 

 

+main(args: String[]): void

 

 

 

 

 

 

 

 

FIGURE 17.32 MultipleWindowsDemo uses Histogram to display a histogram of the occurrences of the letters in a text area in the frame.

MultipleWindowsDemo is a frame that holds a text area in a scroll pane and a button. Histogram is a subclass of JPanel that displays a histogram for the occurrences of letters in the text area.

When the user clicks the Show Histogram button, the handler counts the occurrences of letters in the text area. Letters are counted regardless of their case. Nonletter characters are not counted. The count is stored in an int array of 26 elements. The first element in the array stores the count for letter 'a' or 'A', and the last element stores the count for letter 'z' or 'Z'. The count array is passed to the histogram for display.

The MultipleWindowsDemo class contains a main method. The main method creates an instance of MultipleWindowsDemo and displays the frame. The MultipleWindowsDemo class also contains an instance of JFrame, named histogramFrame, which holds an instance of Histogram. When the user clicks the Show Histogram button, histogramFrame is set visible to display the histogram.

The height and width of the bars in the histogram are determined dynamically according to the window size of the histogram.

606 Chapter 17 Creating Graphical User Interfaces

You cannot add an instance of JFrame to a container. For example, adding histogramFrame to the main frame would cause a runtime exception. However, you can create a frame instance and set it visible to launch a new window.

CHAPTER SUMMARY

1.You learned how to create graphical user interfaces using Swing GUI components

JButton, JCheckBox, JRadioButton, JLabel, JTextField, JTextArea,

JComboBox, JList, JScrollBar, and JSlider. You also learned how to handle events on these components.

2.You can display a text and icon on buttons (JButton, JCheckBox, JRadioButton) and labels (JLabel).

REVIEW QUESTIONS

Sections 17.2–17.4

17.1How do you create a button labeled OK? How do you change text on a button? How do you set an icon, a pressed icon, and a rollover icon in a button?

17.2Given a JButton object jbtOK, write statements to set the button’s foreground to red, background to yellow, mnemonic to 'K', tool tip text to "Click OK to proceed", horizontal alignment to RIGHT, vertical alignment to BOTTOM, horizontal text position to LEFT, vertical text position to TOP, and icon text gap to 5.

17.3How do you create a check box? How do you create a check box with the box checked initially? How do you determine whether a check box is selected?

17.4How do you create a radio button? How do you create a radio button with the button selected initially? How do you group the radio buttons together? How do you determine whether a radio button is selected?

17.5List at least five properties defined in the AbstractButton class.

Sections 17.5–17.9

17.6How do you create a label named "Address"? How do you change the name on a label? How do you set an icon in a label?

17.7Given a JLabel object jlblMap, write statements to set the label’s foreground to red, background to yellow, mnemonic to 'K', tool tip text to "Map image", horizontal alignment to RIGHT, vertical alignment to BOTTOM, horizontal text position to LEFT, vertical text position to TOP, and icon text gap to 5.

17.8How do you create a text field with 10 columns and the default text "Welcome to Java"? How do you write the code to check whether a text field is empty?

17.9How do you create a text area with ten rows and 20 columns? How do you insert three lines into the text area? How do you create a scrollable text area?

17.10How do you create a combo box, add three items to it, and retrieve a selected item?

17.11How do you create a list with an array of strings?

Sections 17.10–17.12

17.12How do you create a horizontal scroll bar? What event can a scroll bar fire?

17.13How do you create a vertical slider? What event can a slider fire?

17.14Explain how to create and show multiple frames in an application.

Programming Exercises 607

PROGRAMMING EXERCISES

Pedagogical Note

Instructors may assign the exercises from the next chapter as exercises for this chapter.

additional exercises

Instead of writing Java applets, ask students to write Java applications.

 

Sections 17.2–17.5

17.1* (Revising Listing 17.2, ButtonDemo.java) Rewrite Listing 17.2 to add a group of radio buttons to select background colors. The available colors are red, yellow, white, gray, and green (see Figure 17.33).

FIGURE 17.33 The 6 = and = 7 buttons move the message on the panel, and you can also set the background color for the message.

17.2* (Selecting geometric figures) Write a program that draws various figures, as shown in Figure 17.34. The user selects a figure from a radio button and specifies whether it is filled in a check box. (Hint: Use the FigurePanel class introduced in Listing 15.3 to display a figure.)

FigurePanel

Panel with

FlowLayout

FIGURE 17.34 The program displays lines, rectangles, and ovals when you select a shape type.

17.3** (Traffic lights) Write a program that simulates a traffic light. The program lets the user select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a time (see Figure 17.35). No light is on when the program starts.

Traffic light panel

Panel with

FlowLayout

FIGURE 17.35 The radio buttons are grouped to let you select only one color in the group to control a traffic light.

608 Chapter 17 Creating Graphical User Interfaces

Sections 17.6–17.10

17.4** (Text Viewer) Write a program that displays a text file in a text area, as shown in Figure 17.36. The user enters a file name in a text field and clicks the View button; the file is then displayed in a text area.

(a)

(b)

FIGURE 17.36 (a) The program displays the text from a file to a text area. (b) The program displays a histogram that shows the occurrences of each letter in the file.

17.5** (Creating a histogram for occurrences of letters) In Listing 17.12, MultipleWindowsDemo.java, you developed a program that displays a histogram to show the occurrences of each letter in a text area. Reuse the Histogram class created in Listing 17.12 to write a program that will display a histogram on a panel. The histogram should show the occurrences of each letter in a text file, as shown in Figure 17.36(b). Assume that the letters are not case sensitive.

Place a panel that will display the histogram in the center of the frame.

Place a label and a text field in a panel, and put the panel in the south side of the frame. The text file will be entered from this text field.

Pressing the Enter key on the text field causes the program to count the occurrences of each letter and display the count in a histogram.

17.6* (Creating a miles/kilometers converter) Write a program that converts miles and kilometers, as shown in Figure 17.37. If you enter a value in the Mile text field and press the Enter key, the corresponding kilometer is displayed in the Kilometer text field. Likewise, if you enter a value in the Kilometer text field and press the Enter key, the corresponding mile is displayed in the Mile text field.

 

Panel with BorderLayout

Panel with GridLayout

Panel with GridLayout for

for two labels

two text fields

 

FIGURE 17.37 The program converts miles to kilometers, and vice versa.

17.7* (Setting clock time) Write a program that displays a clock time and sets it with the input from three text fields, as shown in Figure 17.38. Use the StillClock in Listing 15.10.

17.8** (Selecting a font) Write a program that can dynamically change the font of a message to be displayed on a panel. The message can be displayed in bold and italic at the same time, or can be displayed in the center of the panel. You can select the font name or font size from combo boxes, as shown in Figure 17.39. The available font names can be obtained using getAvailableFontFamilyNames() in GraphicsEnvironment (§12.8, “The Font Class”). The combo box for font size is initialized with numbers from 1 to 100.

Programming Exercises 609

StillClock

Panel with FlowLayout

FIGURE 17.38 The program displays the time specified in the text fields.

Panel with BorderLayout

Panel with

 

Panel with BorderLayout

BorderLayout

 

FIGURE 17.39 You can dynamically set the font for the message.

17.9** (Demonstrating JLabel properties) Write a program to let the user dynamically set the properties horizontalAlignment, verticalAlignment, horizontalTextAlignment, and verticalTextAlignment, as shown in Figure 17.40.

Panel with GridLayout

Panel with BorderLayout

Panel with BorderLayout

Panel with

Panel with GridLayout

GridLayout

for two combo boxes

Panel with GridLayout

Panel with GridLayout

for two combo boxes

for two labels

FIGURE 17.40 You can set the alignment and text-position properties of a button dynamically.

17.10* (Adding new features into Listing 17.2, ButtonDemo.java, incrementally) Improve Listing 17.2 incrementally, as follows (see Figure 17.41):

1.Add a text field labeled "Enter a new message" in the same panel with the buttons. When you type a new message in the text field and press the Enter key, the new message is displayed in the message panel.

2.Add a combo box labeled "Select an interval" in the same panel with the buttons. The combo box enables the user to select a new interval for moving the message. The selection values range from 5 to 100 with interval 5. The user can also type a new interval in the combo box.

3.Add three radio buttons that enable the user to select the foreground color for the message as Red, Green, and Blue. The radio buttons are grouped in a panel, and the panel is placed in the north of the frame’s content pane.

610Chapter 17 Creating Graphical User Interfaces

4.Add three check boxes that enable the user to center the message and display it in italic or bold. Place the check boxes in the same panel with the radio buttons.

5.Add a border titled "Message Panel" on the message panel, add a border titled "South Panel" on the panel for buttons, and add a border titled "North Panel" on the panel for radio buttons and check boxes.

Panel with FlowLayout

MessagePanel

Panel with FlowLayout

FIGURE 17.41 The program uses buttons, labels, text fields, combo boxes, radio buttons, check boxes, and borders.

17.11*(Demonstrating JTextField properties) Write a program that sets the horizon- tal-alignment and column-size properties of a text field dynamically, as shown in Figure 17.42.

Video Note

Use text areas

FIGURE 17.42 You can set the horizontal-alignment and column-size properties of a text field dynamically.

17.12*(Demonstrating JTextArea properties) Write a program that demonstrates the wrapping styles of the text area. The program uses a check box to indicate whether the text area is wrapped. In the case where the text area is wrapped, you need to specify whether it is wrapped by characters or by words, as shown in Figure 17.43.

JTextArea inside a scroll pane

Panel with

FlowLayout

FIGURE 17.43 You can set the options to wrap a text area by characters or by words dynamically.

17.13*(Comparing loans with various interest rates) Rewrite Exercise 4.21 to create a user interface, as shown in Figure 17.44. Your program should let the user enter the loan amount and loan period in number of years from a text field, and should display the monthly and total payments for each interest rate starting from 5 percent to 8 percent, with increments of one-eighth, in a text area.

Programming Exercises 611

Panel with

FlowLayout

JTextArea inside a scroll pane

FIGURE 17.44 The program displays a table for monthly payments and total payments on a given loan based on various interest rates.

17.14* (Using JComboBox and JList) Write a program that demonstrates selecting items in a list. The program uses a combo box to specify a selection mode, as shown in Figure 17.45. When you select items, they are displayed in a label below the list.

JComboBox

JList inside a scroll pane

JLabel

FIGURE 17.45 You can choose single selection, single-interval selection, or multiple-interval selection in a list.

Sections 17.11–17.13

17.15** (Using JScrollBar) Write a program that uses scroll bars to select the foreground color for a label, as shown in Figure 17.46. Three horizontal scroll bars are used for selecting the red, green, and blue components of the color. Use a title border on the panel that holds the scroll bars.

Panel with

Panel with BorderLayout

 

GridLayout

 

for three labels

Panel with GridLayout

 

for three scroll bars

FIGURE 17.46 The foreground color changes in the label as you adjust the scroll bars.

17.16** (Using JSlider) Revise the preceding exercise using sliders.

17.17*** (Displaying a calendar) Write a program that displays the calendar for the current month, as shown in Figure 17.47. Use labels, and set texts on the labels to display the calendar. Use the GregorianCalendar class in §14.3, “Example: Calendar and GregorianCalendar,” to obtain the information about month, year, first day of the month, and number of days in the month.

612 Chapter 17 Creating Graphical User Interfaces

JLabel

JPanel with GridLayout

Each cell is a JLabel

FIGURE 17.47 The program displays the calendar for the current month.

17.18* (Revising Listing 17.12, MultipleWindowsDemo.java) Instead of displaying the occurrences of the letters using the Histogram component in Listing 17.12, use a bar chart, so that the display is as shown in Figure 17.48.

FIGURE 17.48 The number of occurrences of each letter is displayed in a bar chart.

17.19** (Displaying country flag and flag description) Listing 17.8, ComboBoxDemo.java, gives a program that lets users view a country’s flag image and description by selecting the country from a combo box. The description is a string coded in the program. Rewrite the program to read the text description from a file. Suppose that the descriptions are stored in the file description0.txt, Á , and description8.txt under the text directory for the nine countries Canada, China, Denmark, France, Germany, India, Norway, the United Kingdom, and the United States, in this order.

17.20** (Slide show) Exercise 16.13 developed a slide show using images. Rewrite Exercise 16.13 to develop a slide show using text files. Suppose ten text files named slide0.txt, slide1.txt, Á , and slide9.txt are stored in the text directory. Each slide displays the text from one file. Each slide is shown for a second. The slides are displayed in order. When the last slide finishes, the first slide is redisplayed, and so on. Use a text area to display the slide.

CHAPTER 18

APPLETS AND MULTIMEDIA

Objectives

To convert GUI applications to applets (§18.2).

To embed applets in Web pages (§18.3).

To run applets from Web browsers and from the appletviewer (§§18.3.1–18.3.2).

To understand the applet security sandbox model (§18.4).

To write a Java program that can run both as an application and as an applet (§18.5).

To override the applet life-cycle methods init, start, stop, and destroy (§18.6).

To pass string values to applets from HTML (§18.7).

To develop an animation for a bouncing ball (§18.8).

To develop an applet for the TicTacToe game (§18.9).

To locate resources (images and audio) using the URL class (§18.10).

To play audio in any Java program (§18.11).

Тут вы можете оставить комментарий к выбранному абзацу или сообщить об ошибке.

Оставленные комментарии видны всем.

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