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

422 Chapter 12

GUI Basics

 

25

 

JPanel p2 = new JPanel(new GridLayout(1, 2, 5, 5));

 

26

 

JLabel jlblRed = new JLabel("Red");

 

27

JLabel jlblOrange = new JLabel("Orange");

set foreground

28

 

jlblRed.setForeground(Color.RED);

 

29

 

jlblOrange.setForeground(Color.ORANGE);

 

set font

30

 

jlblRed.setFont(largeFont);

 

 

 

31

 

jlblOrange.setFont(largeFont);

set line border

32

 

jlblRed.setBorder(lineBorder);

 

 

 

33

 

jlblOrange.setBorder(lineBorder);

 

34

 

p2.add(jlblRed);

 

35

 

p2.add(jlblOrange);

set titled border

36

 

p2.setBorder(new TitledBorder("Two Labels"));

 

 

37

 

 

 

 

 

 

 

38

 

// Add two panels to the frame

 

39

 

setLayout(new GridLayout(2, 1, 5, 5));

 

40

 

add(p1);

 

41

 

add(p2);

 

42

}

 

 

 

 

 

 

43

 

 

 

 

 

 

 

44

public static void main(String[] args) {

 

45

 

// Create a frame and set its properties

 

46

 

JFrame frame = new TestSwingCommonFeatures();

 

47

 

frame.setTitle("TestSwingCommonFeatures");

 

48

 

frame.setSize(300, 150);

 

49

 

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

 

50

 

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

51

 

frame.setVisible(true);

 

52

}

 

 

 

 

 

 

53

}

 

 

 

 

 

 

 

Note

property default values

 

The same property may have different default values in different components. For example, the

 

 

visible property in JFrame is false by default, but it is true in every instance of

 

 

JComponent (e.g., JButton and JLabel) by default. To display a JFrame, you have to

 

 

invoke setVisible(true) to set the visible property true, but you don’t have to set this

 

 

property for a JButton or a JLabel, because it is already true. To make a JButton or a

 

 

JLabel invisible, you may invoke setVisible(false). Please run the program and see the

 

 

effect after inserting the following two statements in line 37:

 

 

jbtLeft.setVisible(false);

 

 

jlblRed.setVisible(false);

 

12.10 Image Icons

 

An icon is a fixed-size picture; typically it is small and used to decorate components. Images

 

are normally stored in image files. Java currently supports three image formats: GIF (Graph-

 

ics Interchange Format), JPEG (Joint Photographic Experts Group), and PNG (Portable Net-

 

work Graphics). The image file names for these types end with .gif, .jpg, and .png,

image-file format

respectively. If you have a bitmap file or image files in other formats, you can use image-pro-

 

cessing utilities to convert them into GIF, JPEG, or PNG format for use in Java.

 

To display an image icon, first create an ImageIcon object using new

 

javax.swing.ImageIcon(filename). For example, the following statement creates an

 

icon from an image file us.gif in the image directory under the current class path:

create ImageIcon

ImageIcon icon = new ImageIcon("image/us.gif");

 

image/us.gif” is located in “c:\book\image\us.gif.” The back slash (\) is the

file path character

Windows file path notation. In Unix, the forward slash (/) should be used. In Java, the forward

12.10 Image Icons 423

slash (/) is used to denote a relative file path under the Java classpath (e.g., image/us.gif, as in this example).

Tip

File names are not case sensitive in Windows but are case sensitive in Unix. To enable your pro-

 

grams to run on all platforms, name all the image files consistently, using lowercase.

naming files consistently

An image icon can be displayed in a label or a button using new JLabel(imageIcon) or new JButton(imageIcon). Listing 12.8 demonstrates displaying icons in labels and buttons. The example creates two labels and two buttons with icons, as shown in Figure 12.13.

LISTING 12.8 TestImageIcon.java

1

import javax.swing.*;

 

 

2

import java.awt.*;

 

 

3

 

 

 

 

4

public class TestImageIcon

extends JFrame {

 

5

 

private ImageIcon usIcon

= new ImageIcon("image/us.gif");

create image icons

6

private ImageIcon myIcon

= new ImageIcon("image/my.jpg");

 

7

private ImageIcon frIcon

= new ImageIcon("image/fr.gif");

 

8

private ImageIcon ukIcon = new ImageIcon("image/uk.gif");

 

9

 

 

 

 

10public TestImageIcon() {

11setLayout(new GridLayout(1, 4, 5, 5));

12

 

add(new JLabel(usIcon));

 

a label with image

13

add(new

JLabel(myIcon));

 

14

 

add(new

JButton(frIcon));

a button with image

15add(new JButton(ukIcon));

16}

17

18/** Main method */

19public static void main(String[] args) {

20TestImageIcon frame = new TestImageIcon();

21frame.setTitle("TestImageIcon");

22frame.setSize(200, 200);

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

24frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

25frame.setVisible(true);

26}

27}

FIGURE 12.13 The image icons are displayed in labels and buttons.

Note

GUI components cannot be shared by containers, because one GUI component can appear in only one container at a time. Therefore, the relationship between a component and a container is the composition denoted by a solid diamond, as shown in Figure 12.1.

424 Chapter 12

GUI Basics

 

 

 

 

 

Note

 

 

 

sharing borders and icons

 

Borders and icons can be shared. Thus you can create a border or icon and use it to set the

 

 

border or icon property for any GUI component. For example, the following statements set a

 

 

border b for two panels p1 and p2:

 

 

 

 

p1.setBorder(b);

 

 

 

 

 

p2.setBorder(b);

 

 

 

 

 

The following statements set an icon in two buttons jbt1 and jbt2:

 

 

 

jbt1.setIcon(icon);

 

 

 

 

jbt2.setIcon(icon);

 

 

 

 

Tip

 

 

 

splash screen

 

A splash screen is an image that is displayed while the application is starting up. If your program

 

 

takes a long time to load, you may display a splash screen to alert the user. For example, the fol-

 

 

lowing command:

 

 

 

 

 

java –splash:image/us.gif TestImageIcon

 

 

 

displays an image while the program TestImageIcon is being loaded.

 

 

 

KEY TERMS

 

 

 

 

 

AWT 406

 

layout manager

411

 

 

heavyweight component

406

Swing 406

 

 

 

lightweight component

406

splash screen

424

CHAPTER SUMMARY

1.Every container has a layout manager that is used to position and place components in the container in the desired locations. Three simple and frequently used layout managers are FlowLayout, GridLayout, and BorderLayout.

2.You can use a JPanel as a subcontainer to group components to achieve a desired layout.

3.Use the add method to place components to a JFrame or a JPanel. By default, the frame’s layout is BorderLayout, and the JPanel’s layout is FlowLayout.

4.You can set colors for GUI components by using the java.awt.Color class. Colors are made of red, green, and blue components, each represented by an unsigned byte value that describes its intensity, ranging from 0 (darkest shade) to 255 (lightest shade). This is known as the RGB model.

5.To create a Color object, use new Color(r, g, b), in which r, g, and b specify a color by its red, green, and blue components. Alternatively, you can use one of the 13 standard colors (BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW) defined as constants in java.awt.Color.

6.Every Swing GUI component is a subclass of javax.swing.JComponent, and

JComponent is a subclass of java.awt.Component. The properties font, background, foreground, height, width, and preferredSize in Component are inherited in these subclasses, as are toolTipText and border in JComponent.

7.You can use borders on any Swing components. You can create an image icon using the ImageIcon class and display it in a label and a button. Icons and borders can be shared.

Review Questions 425

REVIEW QUESTIONS

Sections 12.3–12.4

12.1Which class is the root of the Java GUI component classes? Is a container class a subclass of Component? Which class is the root of the Swing GUI component classes?

12.2Explain the difference between AWT GUI components, such as java.awt.Button, and Swing components, such as javax.swing.JButton.

12.3How do you create a frame? How do you set the size for a frame? How do you get the size of a frame? How do you add components to a frame? What would happen if the statements frame.setSize(400, 300) and frame.setVisible(true) were swapped in Listing 12.2 MyFrameWithComponents?

12.4Determine whether the following statements are true or false:

You can add a button to a frame.

You can add a frame to a panel.

You can add a panel to a frame.

You can add any number of components to a panel or a frame.

You can derive a class from JButton, JPanel, or JFrame.

12.5The following program is supposed to display a button in a frame, but nothing is displayed. What is the problem?

1 public class Test extends javax.swing.JFrame {

2public Test() {

3add(new javax.swing.JButton("OK"));

4

}

5

 

6public static void main(String[] args) {

7 javax.swing.JFrame frame = new javax.swing.JFrame();

8frame.setSize(100, 200);

9 frame.setVisible(true);

10}

11}

12.6Which of the following statements have syntax errors?

Component c1 = new Component(); JComponent c2 = new JComponent(); Component c3 = new JButton(); JComponent c4 = new JButton(); Container c5 = new JButton(); c5.add(c4);

Object c6 = new JButton(); c5.add(c6);

Sections 12.5

12.7Why do you need to use layout managers? What is the default layout manager for a frame? How do you add a component to a frame?

12.8Describe FlowLayout. How do you create a FlowLayout manager? How do you add a component to a FlowLayout container? Is there a limit to the number of components that can be added to a FlowLayout container?

12.9Describe GridLayout. How do you create a GridLayout manager? How do you add a component to a GridLayout container? Is there a limit to the number of components that can be added to a GridLayout container?

426 Chapter 12 GUI Basics

12.10Describe BorderLayout. How do you create a BorderLayout manager? How do you add a component to a BorderLayout container?

Section 12.6

12.11How do you create a panel with a specified layout manager?

12.12What is the default layout manager for a JPanel? How do you add a component to a JPanel?

12.13Can you use the setTitle method in a panel? What is the purpose of using a panel?

12.14Since a GUI component class such as JButton is a subclass of Container, can you add components into a button?

Sections 12.7–12.8

12.15How do you create a color? What is wrong about creating a Color using new Color(400, 200, 300)? Which of two colors is darker, new Color(10, 0, 0) or new Color(200, 0, 0)?

12.16How do you create a font? How do you find all available fonts on your system?

Sections 12.9–12.10

12.17How do you set background color, foreground color, font, and tool tip text on a Swing GUI component? Why is the tool tip text not displayed in the following code?

1 import javax.swing.*;

2

3 public class Test extends JFrame {

4 private JButton jbtOK = new JButton("OK");

5

6 public static void main(String[] args) {

7 // Create a frame and set its properties

8JFrame frame = new Test();

9frame.setTitle("Logic Error");

10frame.setSize(200, 100);

11frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

12frame.setVisible(true);

13}

14

15public Test() {

16jbtOK.setToolTipText("This is a button");

17add(new JButton("OK"));

18}

19}

12.18Show the output of the following code:

import javax.swing.*;

public class Test {

public static void main(String[] args) { JButton jbtOK = new JButton("OK"); System.out.println(jbtOK.isVisible());

JFrame frame = new JFrame(); System.out.println(frame.isVisible());

}

}

Programming Exercises 427

12.19How do you create an ImageIcon from the file image/us.gif in the class directory?

12.20What happens if you add a button to a container several times, as shown below? Does it cause syntax errors? Does it cause runtime errors?

JButton jbt = new JButton(); JPanel panel = new JPanel(); panel.add(jbt); panel.add(jbt); panel.add(jbt);

12.21Will the following code display three buttons? Will the buttons display the same icon?

1

import

javax.swing.*;

2

import

java.awt.*;

3

 

 

4

public

class Test extends JFrame {

5

public static void main(String[] args) {

6

//

Create a frame and set its properties

7JFrame frame = new Test();

8 frame.setTitle("ButtonIcons");

9frame.setSize(200, 100);

10frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

11frame.setVisible(true);

12}

13

14public Test() {

15ImageIcon usIcon = new ImageIcon("image/us.gif");

16JButton jbt1 = new JButton(usIcon);

17JButton jbt2 = new JButton(usIcon);

18

19JPanel p1 = new JPanel();

20p1.add(jbt1);

21

22JPanel p2 = new JPanel();

23p2.add(jbt2);

24

25JPanel p3 = new JPanel();

26p2.add(jbt1);

27

28add(p1, BorderLayout.NORTH);

29add(p2, BorderLayout.SOUTH);

30add(p3, BorderLayout.CENTER);

31}

32}

12.22Can a border or an icon be shared by GUI components?

PROGRAMMING EXERCISES

Sections 12.5–12.6

12.1(Using the FlowLayout manager) Write a program that meets the following requirements (see Figure 12.14):

Create a frame and set its layout to FlowLayout.

Create two panels and add them to the frame.

Each panel contains three buttons. The panel uses FlowLayout.

428 Chapter 12 GUI Basics

FIGURE 12.14 Exercise 12.1 places the first three buttons in one panel and the other three buttons in another panel.

12.2(Using the BorderLayout manager) Rewrite the preceding program to create the same user interface, but instead of using FlowLayout for the frame, use BorderLayout. Place one panel in the south of the frame and the other in the center.

12.3(Using the GridLayout manager) Rewrite the preceding program to create the same user interface. Instead of using FlowLayout for the panels, use a GridLayout of two rows and three columns.

12.4(Using JPanel to group buttons) Rewrite the preceding program to create the same user interface. Instead of creating buttons and panels separately, define a class that extends the JPanel class. Place three buttons in your panel class, and create two panels from the user-defined panel class.

12.5(Displaying labels) Write a program that displays four lines of text in four labels, as shown in Figure 12.15(a). Add a line border on each label.

(a)

(b)

(c)

FIGURE 12.15 (a) Exercise 12.5 displays four labels. (b) Exercise 12.6 displays four icons.

(c) Exercise 12.7 displays a TicTacToe board with image icons in labels.

Sections 12.7–12.10

12.6(Displaying icons) Write a program that displays four icons in four labels, as shown in Figure 12.15(b). Add a line border on each label. (Use any images of your choice or those in the book, which can be obtained along with the book’s source code.)

12.7** (Game: displaying a TicTacToe board) Display a frame that contains nine labels. A label may display an image icon for X, an image icon for O, or nothing, as shown in Figure 12.15(c). What to display is randomly decided. Use the Math.random() method to generate an integer 0, 1, or 2, which corresponds to displaying a cross image icon, a not image icon, or nothing. The cross and not images are in the files x.gif and o.gif, which are under the image directory in www.cs.armstrong.edu/liang/intro8e/book.zip).

12.8* (Swing common features) Display a frame that contains six labels. Set the background of the labels to white. Set the foreground of the labels to black, blue, cyan, green, magenta, and orange, respectively, as shown in Figure 12.16(a). Set the border of each label to a line border with the yellow color. Set the font of each label to TimesRoman, bold, and 20 pixels. Set the text and tool tip text of each label to the name of its foreground color.

Programming Exercises 429

(a)

(b)

(c)

FIGURE 12.16 (a) Six labels are placed in the frame. (b) Three cards are randomly selected.

(c) A checkerboard is displayed using buttons.

12.9* (Game: displaying three cards) Display a frame that contains three labels. Each label displays a card, as shown in Figure 12.16(b). The card image files are named 1.png, 2.png, Á , 54.png and stored in the image/card directory. All three cards are distinct and selected randomly. The image files can be obtained from www.cs.armstrong.edu/liang/intro8e/book.zip.

12.10* (Game: displaying a checkerboard) Write a program that displays a checkerboard in which each white and black cell is a JButton with a background black or white, as shown in Figure 12.16(c).

Video Note

Display a checker board

This page intentionally left blank

CHAPTER 13

EXCEPTION HANDLING

Objectives

To get an overview of exceptions and exception handling (§13.2).

To explore the advantages of using exception handling (§13.3).

To distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked vs. unchecked (§13.4).

To declare exceptions in a method header (§13.5.1).

To throw exceptions in a method (§13.5.2).

To write a try-catch block to handle exceptions (§13.5.3).

To explain how an exception is propagated (§13.5.3).

To use the finally clause in a try-catch block (§13.6).

To use exceptions only for unexpected errors (§13.7).

To rethrow exceptions in a catch block (§13.8).

To create chained exceptions (§13.9).

To define custom exception classes (§13.10).

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