Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
630
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

mouse, the keyboard or another form of input, such as voice recognition. In this chapter and Chapter

22, GUI Components: Part 2, you will learn about many of Java's GUI components. [Note: Several concepts covered in this chapter have already been covered in the optional GUI and Graphics Case Study of Chapters 310. So, some material will be repetitive if you read the case study. You do not need to read the case study to understand this chapter.]

[Page 512 (continued)]

11.2. Simple GUI-Based Input/Output with JOptionPane

The applications in Chapters 210 display text at the command window and obtain input from the command window. Most applications you use on a daily basis use windows or dialog boxes (also called dialogs) to interact with the user. For example, e-mail programs allow you to type and read messages in a window provided by the e-mail program. Typically, dialog boxes are windows in which programs display important messages to the user or obtain information from the user. Java's JOptionPane class (package javax.swing) provides prepackaged dialog boxes for both input and output. These dialogs are displayed by invoking static JOptionPane methods. Figure 11.2 presents a simple addition application that uses two input dialogs to obtain integers from the user and a message dialog to display the sum of the integers the user enters.

Figure 11.2. JOptionPane input and message dialogs used to input values from the user and display results.

(This item is displayed on page 513 in the print version)

1

//

Fig. 11.

2: Addition.java

2

//

Addition

program that uses JOptionPane for input and output.

3

import javax.swing.JOptionPane; // program uses JOptionPane

4

 

 

 

5public class Addition

6{

7public static void main( String args[] )

8{

9// obtain user input from JOptionPane input dialogs

10String firstNumber =

11JOptionPane.showInputDialog( "Enter first integer" );

12String secondNumber =

13JOptionPane.showInputDialog( "Enter second integer" );

15 // convert String inputs to int values for use in a calculation

16int number1 = Integer.parseInt( firstNumber );

17int number2 = Integer.parseInt( secondNumber );

19int sum = number1 + number2; // add numbers

21// display result in a JOptionPane message dialog

22JOptionPane.showMessageDialog( null, "The sum is " + sum,

23"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );

24} // end method main

25} // end class Addition

[View full size image]

Line 3 imports class JOptionPane for use in this application. Lines 1011 declare the local String variable firstNumber and assign it the result of the call JOptionPane static method showInputDialog. This method displays an input dialog (see the first screen capture in Fig. 11.2), using the method's String argument ("Enter first integer") as a prompt to the user.

[Page 514]

Look-and-Feel Observation 11.2

The prompt in an input dialog typically uses sentence-style capitalizationa style that capitalizes only the first letter of the first word in the text unless the word is a proper noun (for example, Deitel).

The user types characters in the text field, then clicks the OK button or presses the Enter key to submit the String to the program. Clicking OK also dismisses (hides) the dialog. [Note: If you type in the text field and nothing appears, activate the text field by clicking it with the mouse.] Unlike Scanner, which can be used to input values of several types from the user at the keyboard, an input dialog can input only input Strings. This is typical of most GUI components. Technically, the user can type anything in the input dialog's text field. Our program assumes that the user enters a valid integer value. If the user clicks the Cancel button, showInputDialog returns null. If the user either types a noninteger value or clicks the Cancel button in the input dialog, a runtime logic error will occur in this program and it will not operate correctly. Chapter 13, Exception Handling, discusses how to handle such errors. Lines 1213 display another input dialog that prompts the user to enter the second integer.

To perform the calculation in this application, we must convert the Strings that the user entered to int values. Recall from Section 7.12 that the Integer class's static method parseInt converts its String argument to an int value. Lines 1617 assign the converted values to local variables number1 and number2. Then, line 19 sums these values and assigns the result to local variable sum.

Lines 2223 use JOptionPane static method showMessageDialog to display a message dialog (the last screen capture of Fig. 11.2) containing the sum. The first argument helps the Java application determine where to position the dialog box. The value null indicates that the dialog should appear in

the center of the computer screen. The first argument can also be used to specify that the dialog should appear centered over a particular window, which we will demonstrate later in Section 11.8. The second argument is the message to displayin this case, the result of concatenating the String "The sum is " and the value of sum. The third argument"Sum of Two Integers"represents the string that should appear in the dialog's title bar at the top of the dialog. The fourth

argumentJOptionPane.PLAIN_MESSAGEis the type of message dialog to display. A PLAIN_MESSAGE dialog does not display an icon to the left of the message. Class JOptionPane provides several overloaded versions of methods showInputDialog and showMessageDialog, as well as methods that display other dialog types. For complete information on class JOptionPane, visit java.sun.com/j2se/1.5.0/docs/api/javax/swing/JOptionPane.html.

Look-and-Feel Observation 11.3

The title bar of a window typically uses book-title capitalizationa style that capitalizes the first letter of each significant word in the text and does not end with any punctuation (for example, Capitalization in a Book Title).

JOptionPane Message Dialog Constants

The constants that represent the message dialog types are shown in Fig. 11.3. All message dialog types except PLAIN_MESSAGE display an icon to the left of the message. These icons provide a visual indication of the message's importance to the user. Note that a QUESTION_MESSAGE icon is the default icon for an input dialog box (see Fig. 11.2).

Figure 11.3. JOptionPane static constants for message dialogs.

(This item is displayed on page 515 in the print version)

Message dialog type

Icon

Description

 

 

 

ERROR_MESSAGE

 

A dialog that indicates an error to the user.

INFORMATION_MESSAGE

 

A dialog with an informational message to the user.

WARNING_MESSAGE

 

A dialog warning the user of a potential problem.

QUESTION_MESSAGE

 

A dialog that poses a question to the user. This dialog

 

 

normally requires a response, such as clicking a Yes or

 

 

a No button.

PLAIN_MESSAGE

no icon

A dialog that contains a message, but no icon.

 

 

 

[Page 515]

11.3. Overview of Swing Components

Though it is possible to perform input and output using the JOptionPane dialogs presented in Section 11.2, most GUI applications require more elaborate, customized user interfaces. The remainder of this chapter discusses many GUI components that enable application developers to create robust GUIs.

Figure 11.4 lists several Swing GUI components from package javax.swing that are used to build Java GUIs. Most Swing components are pure Java componentsthey are written, manipulated and displayed completely in Java. They are part of the Java Foundation Classes (JFC)Java's libraries for cross-platform GUI development. Visit java.sun.com/products/jfc for more information on JFC.

Figure 11.4. Some basic GUI components.

Component

Description

 

 

JLabel

Displays uneditable text or icons.

JTextField

Enables user to enter data from the keyboard. Can also be used to

 

display editable or uneditable text.

JButton

Triggers an event when clicked with the mouse.

JCheckBox

Specifies an option that can be selected or not selected.

JComboBox

Provides a drop-down list of items from which the user can make a

 

selection by clicking an item or possibly by typing into the box.

JList

Provides a list of items from which the user can make a selection by

 

clicking on any item in the list. Multiple elements can be selected.

JPanel

Provides an area in which components can be placed and organized.

 

Can also be used as a drawing area for graphics.

 

 

[Page 516]

Swing vs. AWT

There are actually two sets of GUI components in Java. Before Swing was introduced in J2SE 1.2, Java GUIs were built with components from the Abstract Window Toolkit (AWT) in package java.awt. When a Java application with an AWT GUI executes on different Java platforms, the application's GUI components display differently on each platform. Consider an application that displays an object of type Button (package java.awt). On a computer running the Microsoft Windows operating system, the Button will have the same appearance as the buttons in other Windows applications. Similarly, on a computer running the Apple Mac OS X operating system, the Button will have the same look and feel as the buttons in other Macintosh applications. Sometimes, the manner in which a user can interact with a particular AWT component differs between platforms.

Together, the appearance and the way in which the user interacts with the application are known as that application's look-and-feel. Swing GUI components allow you to specify a uniform look-and-feel for your application across all platforms or to use each platform's custom look-and-feel. An application can even change the look-and-feel during execution to enable users to choose their own preferred look- and-feel.

Portability Tip 11.1

Swing components are implemented in Java, so they are more portable and flexible than the original Java GUI components from

package java.awt, which were based on the GUI components of the underlying platform. For this reason, Swing GUI components are generally preferred.

Lightweight vs. Heavyweight GUI Components

Most Swing components are not tied to actual GUI components supported by the underlying platform on which an application executes. Such GUI components are known as lightweight components. AWT components (many of which parallel the Swing components), are tied to the local platform and are called heavyweight components, because they rely on the local platform's windowing system to determine their functionality and their look-and-feel.

Several Swing components are heavyweight components. Like AWT components, heavyweight Swing GUI components require direct interaction with the local windowing system, which may restrict their appearance and functionality. As you will learn, lightweight components provide you with more control over their appearance and functionality.

Look-and-Feel Observation 11.4

The look and feel of a GUI defined with heavyweight GUI components from package java.awt may vary across platforms. Because heavyweight components are tied to the local-platform GUI, the look and feel varies from platform to platform.

Superclasses of Swing's Lightweight GUI Components

The UML class diagram of Fig. 11.5 shows an inheritance hierarchy containing classes from which lightweight Swing components inherit their common attributes and behaviors. As discussed in Chapter 9, class Object is the superclass of the Java class hierarchy.

Figure 11.5. Common superclasses of many of the Swing components.

(This item is displayed on page 517 in the print version)

[View full size image]

Software Engineering Observation 11.1

Study the attributes and behaviors of the classes in the class hierarchy of Fig. 11.5. These classes declare the features that are common to most Swing components.

[Page 517]

Class Component (package java.awt) is a subclass of Object that declares many of the attributes and behaviors common to the GUI components in packages java.awt and javax.swing. Most GUI components extend class Component directly or indirectly. Visit java.sun.com/j2se/5.0/docs/api/java/awt/Component.html for a complete list of these common features.

Class Container (package java.awt) is a subclass of Component. As you will soon see, Components are attached to Containers (such as windows) so the Components can be organized and displayed on the screen. Any object that is a Container can be used to organize other Components in a GUI. Because a Container is a Component, you can attach Containers to other Containers to help organize a GUI. Visit java.sun.com/j2se/5.0/docs/api/java/awt/Container.html for a complete list of the Container features that are common to Swing lightweight components.

Class JComponent (package javax.swing) is a subclass of Container. JComponent is the superclass of all lightweight Swing components and declares their common attributes and behaviors. Because JComponent is a subclass of Container, all lightweight Swing components are also Containers. Some common lightweight component features supported by JComponent include:

1.A pluggable look-and-feel that can be used to customize the appearance of components (e.g., for use on particular platforms). You will see an example of this in Section 22.6.

2.Shortcut keys (called mnemonics) for direct access to GUI components through the keyboard. You will see an example of this in Section 22.4.

3.Common event-handling capabilities for cases where several GUI components initiate the same actions in an application.

4.Brief descriptions of a GUI component's purpose (called tool tips) that are displayed when the mouse cursor is positioned over the component for a short time. You will see an example of this in the next section.

5.Support for assistive technologies, such as braille screen readers for the visually impaired.

6.Support for user-interface localizationthat is, customizing the user interface to display in different languages and use local cultural conventions.

[Page 518]

These are just some of the many features of the Swing components. Visit java.sun.com/j2se/5.0/docs/api/javax/swing/JComponent.html for more details of the common lightweight component features.

[Page 518 (continued)]

11.4. Displaying Text and Images in a Window

Our next example introduces a framework for building GUI applications. This framework uses several concepts that you will see in many of our GUI applications. This is our first example in which the application appears in its own window. Most windows you will create are an instance of class JFrame or a subclass of JFrame. JFrame provides the basic attributes and behaviors of a windowa title bar at the top of the window, and buttons to minimize, maximize and close the window. Since an application's GUI is typically specific to the application, most of our examples will consist of two classesa subclass of JFrame that helps us demonstrate new GUI concepts and an application class in which main creates and displays the application's primary window.

Labeling GUI Components

A typical GUI consists of many components. In a large GUI, it can be difficult to identify the purpose of every component unless the GUI designer provides text instructions or information stating the purpose of each component. Such text is known as a label and is created with class JLabela subclass of JComponent. A JLabel displays a single line of read-only text, an image, or both text and an image. Applications rarely change a label's contents after creating it.

Look-and-Feel Observation 11.5

Text in a JLabel normally uses sentence-style capitalization.

The application of Fig. 11.6 and Fig. 11.7 demonstrates several JLabel features and presents the framework we use in most of our GUI examples. We did not highlight the code in this example since most of it is new. [Note: There are many more features for each GUI component than we can cover in our examples. To learn the complete details of each GUI component, visit its page in the online documentation. For class JLabel, visit java.sun.com/j2se/5.0/docs/api/javax/swing/JLabel.html.]

Figure 11.6. JLabels with text and icons.

(This item is displayed on page 519 in the print version)

1// Fig. 11.6: LabelFrame.java

2// Demonstrating the JLabel class.

3

import java.awt.FlowLayout; // specifies how

components

are

arranged

4

import javax.swing.JFrame; //

provides

basic

window features

 

5

import javax.swing.JLabel; //

displays

text and images

 

 

6

import javax.swing.SwingConstants; // common

constants

used

with Swing

7

import javax.swing.Icon; // interface used to manipulate images

8

import javax.swing.ImageIcon;

// loads

images

 

 

 

9

 

 

 

 

 

 

10public class LabelFrame extends JFrame

11{

12private JLabel label1; // JLabel with just text

13private JLabel label2; // JLabel constructed with text and icon

14private JLabel label3; // JLabel with added text and icon

15

16// LabelFrame constructor adds JLabels to JFrame

17public LabelFrame()

18{

19super( "Testing JLabel" );

20setLayout( new FlowLayout() ); // set frame layout

22// JLabel constructor with a string argument

23label1 = new JLabel( "Label with text" );

24label1.setToolTipText( "This is label1" );

25add( label1 ); // add label1 to JFrame

27// JLabel constructor with string, Icon and alignment arguments

28Icon bug = new ImageIcon( getClass().getResource( "bug1.gif" ) );

29label2 = new JLabel( "Label with text and icon", bug,

30SwingConstants.LEFT );

31label2.setToolTipText( "This is label2" );

32add( label2 ); // add label2 to JFrame

33

34label3 = new JLabel(); // JLabel constructor no arguments

35label3.setText( "Label with icon and text at bottom" );

36label3.setIcon( bug ); // add icon to JLabel

37label3.setHorizontalTextPosition( SwingConstants.CENTER );

38label3.setVerticalTextPosition( SwingConstants.BOTTOM );

39label3.setToolTipText( "This is label3" );

40add( label3 ); // add label3 to JFrame

41} // end LabelFrame constructor

42} // end class LabelFrame

Figure 11.7. Test class for LabelFrame.

(This item is displayed on page 520 in the print version)

1// Fig. 11.7: LabelTest.java

2// Testing LabelFrame.

3import javax.swing.JFrame;

4

5public class LabelTest

6{

7public static void main( String args[] )

8{

9LabelFrame labelFrame = new LabelFrame(); // create LabelFrame

10labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11labelFrame.setSize( 275, 180 ); // set frame size

12labelFrame.setVisible( true ); // display frame

13} // end main

14} // end class LabelTest

[View full size image]

Class LabelFrame (Fig. 11.6) is a subclass of JFrame. We will use an instance of class LabelFrame to display a window containing three JLabels. Lines 38 import the classes used in class LabelFrame. The class extends JFrame to inherit the features of a window. Lines 1214 declare the three JLabel instance variables, each of which is instantiated in the LabelFrame constructor (lines 1741). Typically, the JFrame subclass's constructor builds the GUI that is displayed in the window when the application executes. Line 19 invokes superclass JFrame's constructor with the argument "Testing JLabel".JFrame's constructor uses this String to specify the text in the window's title bar.

Specifying the Layout

When building a GUI, each GUI component must be attached to a container, such as a window created with a JFrame. Also, you typically must decide where to position each GUI component. This is known as specifying the layout of the GUI components. As you will learn at the end of this chapter and in Chapter 22, Java provides several layout managers that can help you position components.

[Page 519]

Many integrated development environments provide GUI design tools in which you can specify the exact size and location of a component in a visual manner by using the mouse, then the IDE will generate the GUI code for you. Though such IDEs can greatly simplify GUI creation, they are each different in capability.

To ensure that the code in this book can be used with any IDE, we did not use an IDE to create our GUI code. For this reason, we take advantage of Java's various layout managers in our GUI examples. One such layout manager is FlowLayout in which GUI components are placed on a container from left to right in the order in which they are attached to the container by the program. When there is no more room to fit components left to right, components continue to display left to right on the next line. If the container is resized, a FlowLayout reflows (i.e., rearranges) the components to accommodate the new width of the container, possibly with fewer or more rows of GUI components. Line 20 specifies that the layout of the LabelFrame should be a FlowLayout. Method setLayout is inherited into class LabelFrame indirectly from class Container. The argument to the method must be an object of a class that implements the LayoutManager interface, such as an object of class FlowLayout. In this case, we create a new FlowLayout object and pass its reference as the argument to setLayout.

[Page 520]

Creating and Attaching label1

Now that we have specified the layout for the window, we can begin creating and attaching GUI components to the window. Line 23 creates a JLabel object and passes the String "Label with text" to the constructor. The JLabel displays this text when the JLabel appears on the screen as part of the application's GUI. Line 24 uses method setToolTipText (inherited by JLabel from JComponent) to specify the tool tip that is displayed when the user positions the mouse cursor over the JLabel in the GUI. You can see a sample tool tip in the second screen capture of Fig. 11.7. When you execute this application, try positioning the mouse over each JLabel to see its tool tip. Line 25 attaches label1 to the LabelFrame by passing label1 to the add method, which is inherited indirectly from class

Container.

[Page 521]

Common Programming Error 11.1

If you do not explicitly add a GUI component to a container, the GUI component will not be displayed when the container appears on the screen.