Java All-in-One Desk Reference For Dummies phần 7 doc

89 146 0
Java All-in-One Desk Reference For Dummies phần 7 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Some Important Swing Concepts You Need to Know 508 The Swing class hierarchy The Swing API provides many different classes for creating various types of user interface elements. In this chapter, I look at three of those classes: JFrame, JPanel, and JLabel. However, these three classes are part of a larger collection of classes that are all related through inheritance, as shown in Figure 1-2. The Swing family tree splits at the Component class into one group of classes that are derived from the JComponent class, and another branch that descends from the Window class. Object Component Container Frame JPanel JLabel JFrame JComponentWindow Figure 1-2: The Swing family tree. Figure 1-1: A typical Swing window. 39_58961X bk06ch01.qxd 3/29/05 3:44 PM Page 508 Book VI Chapter 1 Swinging into Swing Some Important Swing Concepts You Need to Know 509 The following paragraphs briefly describe each of the classes shown in this figure: ✦ Object: All classes ultimately derive from Object, so it’s no surprise that this class is at the top of the tree. ✦ Component: The Component class represents an object that has a visual representation that can be shown on-screen and that can interact with users. This class defines some basic methods that are available to all Swing classes. For example, the setVisible method determines whether a component is visible or hidden. And the setBounds method sets the location and size of the component. This is an AWT class, not a Swing class. ✦ Container: The Container class builds on the basic visual capabilities of the Component class by adding the ability to hold other containers. This too is an AWT class rather than a Swing class. From this class, you get the add method, which lets you add components to a container. As you’ll see, you use this method in almost all GUI programs. ✦ Window: This class defines a window, which is a specialized type of container object that has a border, a title bar, buttons that minimize, maximize, and close the window, and that can be repositioned and possibly even resized by the user. ✦ Frame: A frame is a type of Window that serves as the basis for Java GUI applications. Frame is an AWT class that has been improved upon by the JFrame class. ✦ JFrame: The Swing version of the older Frame class. Most of your Swing applications include at least one JFrame object. ✦ JComponent: The JComponent class is a Swing class that is the basis for all other Swing components except for frames. ✦ JPanel: This class creates panels, which are containers used to organ- ize and control the layout of other components such as labels, buttons, text fields, and so on. In most Swing applications, one or more panels are added to a frame. Then, when the frame is displayed, the components that were added to its panels are made visible. ✦ JLabel: This class creates a label that displays a simple text value. As you work with Swing, you’ll find that some of the classes you use are defined in the javax.swing package. So you need to start every Swing application with this line: import javax.swing.*; In addition, you’ll find that some Swing features use classes in the java.awt and java.awt.event packages. So you may need to import those packages as well. 39_58961X bk06ch01.qxd 3/29/05 3:44 PM Page 509 I’ve Been Framed! 510 I’ve Been Framed! The top-level component for most Swing-based applications is called a frame and is defined by the JFrame class. By itself, a frame doesn’t do much. But to do anything else in Swing, you must first create a frame. Figure 1-3 shows a frame that does nothing but display the message Hello, World! in its title bar. The JFrame has about a bazillion methods, but only a few of them are useful in most programs. Table 1-1 lists the JFrame methods you use most, along with a couple of constructors. Table 1-1 Useful JFrame Constructors and Methods Constructor Description JFrame() Creates a new frame with no title. JFrame(String title) Creates a new frame with the specified title. Method Description void add(Component c) Adds the specified component to the frame. JMenuBar getJMenuBar() Gets the menu for this frame. void pack() Adjusts the size of the frame to fit the compo- nents you’ve added to it. void remove(Component c) Removes the specified component from the frame. void Sets the action taken when the user closes the setDefaultCloseOperation frame. You should almost always specify JFrame.EXIT_ON_CLOSE. void setIconImage Sets the icon displayed when the frame is (Icon image) minimized. void setLayout Sets the layout manager used to control how (LayoutManager layout) components are arranged when the frame is dis- played. The default is the BorderLayout manager. void setLocation Sets the x and y position of the frame on-screen. (int x, int y) The top-left corner of the screen is 0, 0. Figure 1-3: The frame displayed by the Hello, World! program. 39_58961X bk06ch01.qxd 3/29/05 3:44 PM Page 510 Book VI Chapter 1 Swinging into Swing Hello, World! in Swing 511 Method Description void setLocationRelativeTo Centers the frame on-screen if the parameter is (Component c) null. void setResizeable Sets whether or not the size of the frame can be (boolean value) changed by the user. The default setting is true (the frame can be resized). void setSize(int width, Sets the size of the frame to the specified width int height) and height. void setJMenuBar(JMenuBar Sets the menu for this frame. menu) At the minimum, you want to set a title for a new frame, set the frame’s size so it’s large enough to see any components you add to it (by default, the frame is zero pixels wide and zero pixels high, so it isn’t very useful), and call the setVisible method to make the frame visible. One way to do these three things is to create an instance of the JFrame class and set its properties using statements like this: JFrame frame = new JFrame(“This is the title”); frame.setSize(350, 260); frame.setVisible(true); However, creating a frame by declaring a class that extends the JFrame class is more common. Then, you call these methods in the constructor, as I describe in the next section. By default, the user can change the size of a frame. If you want to fix the size of your frame so the user can’t change it, just call setResizeable(false). Hello, World! in Swing To get you started with Swing, Listing 1-1 shows a Swing version of the clas- sic Hello, World! program, using nothing but a frame. If you run this program, the frame shown in Figure 1-1 is displayed on-screen. As you can see, the frame’s title bar contains the text “Hello, World!” The purpose of this seemingly pointless little program is to illustrate one solution to the first problem you encounter when you work with Swing: The main method is a static method, but Swing frames are objects. So, you have to figure out how to get your program out of a static context. This program does that by creating the application as a class that extends JFrame. Then, the main method calls the class constructor, in effect creating an instance of itself. That’s all the main method does; the real work of this application is done by the constructor. 39_58961X bk06ch01.qxd 3/29/05 3:44 PM Page 511 Hello, World! in Swing 512 LISTING 1-1: THE SWING VERSION OF THE HELLO,WORLD! PROGRAM import javax.swing.*; ➞ 1 public class HelloFrame extends JFrame ➞ 3 { public static void main(String[] args) ➞ 5 { new HelloFrame(); ➞ 7 } public HelloFrame() ➞ 10 { this.setSize(200,100); ➞ 12 this.setDefaultCloseOperation( ➞ 13 JFrame.EXIT_ON_CLOSE); this.setTitle(“Hello World!”); ➞ 15 this.setVisible(true); ➞ 16 } } The following paragraphs describe most of the features of this program: ➞ 1 The program starts with an import statement that imports all the classes in the javax.swing package. Most of the Swing classes are defined in this package. However, you may have to import other classes as well, depending on what GUI features your program uses. ➞ 3 The class for this application, named JFrame, extends a Swing class named JFrame. A class that extends JFrame is often called a frame class. The JFrame class defines a basic frame in which you can display GUI components, such as labels and text boxes. All Swing applications need at least one class that extends JFrame. ➞ 5 Swing applications are still Java applications, and all Java applica- tions need a static main method that starts the application. So the first method listed in this class is the main method. ➞ 7 The first (and only) statement of the main method creates a new instance of the HelloFrame class. Unlike console applications, Swing applications can’t run in a static context. As a result, the main purpose of the static main method in a Swing application is to create an instance of the application’s frame class. ➞ 10 When an instance of the HelloFrame class is created in line 7, the constructor that starts on this line is executed. The main job of the constructor for a frame class is to set the options for the frame and create any GUI components that are displayed in the frame. ➞ 12 The first option that this constructor sets is the size of the frame. To do that, it calls the setSize method. The parameters specify that 39_58961X bk06ch01.qxd 3/29/05 3:44 PM Page 512 Book VI Chapter 1 Swinging into Swing Positioning the Frame On-Screen 513 the frame should be 200 pixels wide and 100 pixels high. (A pixel is one of the little dots that makes up the image on a computer screen. Pixel is short for picture element, but that won’t be on the test.) ➞ 13 The next option this constructor sets is what to do if the user closes the frame by clicking its Close button, which usually appears in the upper-right hand corner of the frame. By default, clicking the Close button hides the frame but doesn’t terminate the application. As a result, the application’s main thread (the one that’s still running in a static context via the main method) keeps running for a while. Eventually, Java figures out that nothing’s happening and shuts the application down. But the application exits more cleanly if you use the setDefaultCloseOperation to set the close operation to JFrame.EXIT_ON_CLOSE. That causes the program to terminate when the frame is closed. ➞ 15 The next statement uses the setTitle method to set the title of the frame. ➞ 16 The last statement in the constructor calls the setVisible method with a parameter value of true, which makes the frame visible on- screen. If you leave this statement out, the frame is created but the user never sees it. That’s all there is to this program. Granted, it’s a little more complicated than the console-base Hello, World! program from Book I, Chapter 1. But not by much. Just to be sure its operation is clear, here’s a recap of what hap- pens when this program is run: 1. Java runs the static main method for the HelloWorld class. 2. The main method creates an instance of the HelloWorld class, which causes the constructor to be executed. 3. The constructor sets the frame size, the default close operation, and the title. 4. Now that the constructor is done, the program continues with the main method, where the setVisible method is called to display the frame. Positioning the Frame On-Screen The JFrame class provides two methods that let you specify the position of the frame on-screen. If you want to place the frame at some arbitrary location on-screen, use the setLocation method. For example, to put the frame at the top left corner of the screen, use this statement: frame.setLocation(0,0); 39_58961X bk06ch01.qxd 3/29/05 3:44 PM Page 513 Using the JPanel Class 514 If you want to center the frame on-screen, call the setLocationRelativeTo method and pass null as the parameter: frame.setLocationRelativeTo(null); This method is designed to let you position a frame relative to some other component that’s already displayed. But if you pass null as the parameter, the method centers the frame on-screen. If you want to position a window at some location other than the top left corner or dead center on-screen, you may need to know the width and height of the user’s screen so you can calculate a location for your frame. To determine the size of the user’s screen, you can use a class named Toolkit. The Toolkit class has a bunch of methods, but you need to know two of them here: ✦ getDefaultToolkit: A static method that creates a Toolkit object. You must use this method before you can use the getScreenSize method. ✦ getScreenSize: Returns the size of the screen as a Dimension object. The Dimension class has two public fields that represent the size of the screen: height and width. Both fields are of type int. Suppose you want to position a frame so that its bottom-left corner is right at the center of the screen. The following code placed in the frame’s constructor does the trick: Toolkit tk = Toolkit.getDefaultToolkit(); Dimension d = tk.getScreenSize(); int x = d.width / 2; int y = (d.height / 2) - this.getHeight(); this.setLocation(x, y); This code first creates a Toolkit object and uses it to get the screen dimensions. It sets the x position to the horizontal center of the screen by dividing the screen width by 2. Then it sets the y position to the vertical center (the screen height divided by 2) less the width of the frame. That puts the bottom of the frame at the vertical midpoint. Using the JPanel Class A panel is a type of container that’s designed to hold a group of components so they can be displayed on a frame. The normal way to display a group of controls such as text fields, labels, buttons, and other GUI widgets is to add those controls to a panel, and then add the panel to the frame. You can bypass the panel and add the controls directly to the frame if you want, but using a separate panel to hold the frames control is almost always a good idea. 39_58961X bk06ch01.qxd 3/29/05 3:44 PM Page 514 Book VI Chapter 1 Swinging into Swing Using the JPanel Class 515 Panels are defined by the JPanel class. Like the JFrame class, the JPanel class has a bevy of methods. Table 1-2 lists the most commonly used con- structors and methods for the JPanel class. Table 1-2 Interesting JPanel Constructors and Methods Constructor Description JPanel() Creates a new panel. JPanel(boolean Creates a new panel. If the parameter is true, the panel isDoubleBuffered) uses a technique called double-buffering, which results in better display for graphics applications. This constructor is usually used for game programs or other panels that display animations. JPanel(LayoutManager Creates a new panel with the specified layout manager. layout) The default layout manager is FlowLayout. Method Description void add(Component c) Adds the specified component to the panel. void remove Removes the specified component from the panel. (Component c) void setLayout Sets the layout manager used to control how components (LayoutManager are arranged when the panel is displayed. The default is layout) the FlowLayout manager. void setLocation(int Sets the x and y position of the frame-screen. The top-left x, int y) corner of the screen is 0, 0. void setSize(int Sets the size of the frame to the specified width and width, int height) height. void setToolTipText Sets the tooltip text that’s displayed if the user rests the (String text) mouse over an empty part of the panel. You can use several different techniques to create a panel and add it to a frame. One is to simply create a JPanel object and assign it to a variable in the JFrame constructor. You can then add components to the panel, and then add the panel to the frame. For example // HelloFrame constructor public HelloFrame() { this.setSize(200,100); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle(“Hello, World!”); JPanel panel = new JPanel(); // code to add components to the panel goes here this.setVisible(true); } 39_58961X bk06ch01.qxd 3/29/05 3:44 PM Page 515 Using Labels 516 Another commonly used technique is to create a separate class for the panel. This class should extend JPanel. Then, you can add any components the panel needs in the constructor: class HelloPanel extends JPanel { public HelloPanel() { // code to add components to the panel goes here } } Then, in the frame class constructor, you create a new instance of the panel class and add it to the panel: HelloPanel panel = new HelloPanel(); this.add(panel); Or, just this statement does the trick: this.add(new HelloPanel()); Using Labels Now that you know how to create frames and panels, you can create a useful component to add to a panel: a label. A label is a component that simply dis- plays text. Labels are used for a variety of purposes: to display captions for other controls such as text fields or combo boxes, to display informational messages, or to show the results of a calculation or a database lookup. A label can also display an image, or it can display both an image and some text. And you have complete control over the appearance of the text: You can specify the font, size, whether the text is bold, italic, or underlined, what color the text is displayed as, and so on. In this chapter, I discuss how to work with basic labels. For more information about additional things you can do with labels, see Book IX, Chapters 1 and 2. To create a label, you use the JLabel class. Table 1-3 shows its most com- monly used constructors and methods. Table 1-3 Tolerable JLabel Constructors and Methods Constructor Description JLabel() Creates a new label with no initial text. JLabel(String text) Creates a new label with the specified text. 39_58961X bk06ch01.qxd 3/29/05 3:44 PM Page 516 [...]... Listener Interfaces Listener Interface Method Description ActionListener (ActionEvent e) ItemListener void actionPerformed Called when an action event occurs void itemStateChanged (ItemEvent e) DocumentListener void changeUpdate (DocumentEvent e) void insertUpdate (DocumentEvent e) void removeUpdate DocumentEvent e) WindowListener void windowActivated (WindowEvent e) void windowClosed (WindowEvent e) void... actionPerformed method is executed when an action event occurs For example, here’s an actionPerformed method that responds to action events: public void actionPerformed(ActionEvent e) { if (e.getSource() == button1) button1.setText(“You clicked!”); } Here, this code changes the text displayed by button1 if the event source is button1 Handling Events 2 Create a class that implements the listener interface for. .. button is clicked Listing 2-1 shows the complete code for this program Figure 2-1: The ClickMe program in action The ClickMe Program 5 27 LISTING 2-1: THE CLICKME PROGRAM import javax.swing.*; import java. awt.event.*; public class ClickMe extends JFrame implements ActionListener { public static void main(String [] args) { new ClickMe(); } ➞ 2 ➞ 5 ➞ 7 ➞ 12 public ClickMe() { this.setSize(200,100); ➞ 14... Events 525 Usually, you declare the variable that refers to the event source as a private class field, outside of the constructor for the frame or any other method For example private JButton button1; Then, in the constructor for the frame class, you can create the button For example, here’s code that creates a panel, creates a button, adds it to a panel, and then adds the panel to the frame: JPanel... listener interface 3 Write the code for any methods defined by the listener When you implement a listener interface, you must provide an implementation of each method defined by the interface Most listener interfaces define just one method, corresponding to the type of event the interface listens for For example, the ActionListener interface defines a method named actionPerformed This method is called whenever... class that handles the events Listing 2-2 shows a version of the ClickMe program that uses an inner class to handle the action event for the button Using Inner Classes to Listen for Events 529 LISTING 2-2: THE CLICKME2 PROGRAM WITH AN INNER CLASS import javax.swing.*; import java. awt.event.*; public class ClickMe2 extends JFrame { public static void main(String [] args) { new ClickMe2(); } private JButton... any way you want Next, you can set up the WindowListener to listen for window events One way to do that is to create an inner class that implements the Window Listener interface Unfortunately, the WindowListener interface has a lot of methods, and you must provide an implementation for each method even if you don’t want to do anything for that method Thus, your Window Listener looks something like this:... AN EXIT BUTTON import javax.swing.*; import java. awt.event.*; public class ClickMe3 extends JFrame { public static void main(String [] args) { new ClickMe3(); } private JButton button1, exitButton; public ClickMe3() { this.setSize( 275 ,100); this.setTitle(“I’m Listening”); this.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE); ClickListener cl = new ClickListener(); ➞ 11 ➞ 17 The ClickMe Program... numeric data into the text fields, as I describe in the section “Using text fields for numeric entry,” later in this chapter Looking at a sample program Figure 3-1: The Namer application in action The code for this program is shown in Listing 3-1 LISTING 3-1: SAYING GOOD MORNING WITH A TEXT FIELD import javax.swing.*; import java. awt.event.*; public class Namer extends JFrame { public static void main(String... can call this method whenever you need to check to see if a text field has a valid integer For example, here’s the actionPerformed method for a program that gets the value entered in a textCount text field and displays it in a JOptionPane message box if the value entered is a valid integer: public void actionPerformed(ActionEvent e) { if (e.getSource() == buttonOK) { if (isInt(textCount, “You must enter . the javax.swing package. So you need to start every Swing application with this line: import javax.swing.*; In addition, you’ll find that some Swing features use classes in the java. awt and java. awt.event. outside of the constructor for the frame or any other method. For example private JButton button1; Then, in the constructor for the frame class, you can create the button. For example, here’s code. inside the actionPerformed method is executed when an action event occurs. For example, here’s an actionPerformed method that responds to action events: public void actionPerformed(ActionEvent

Ngày đăng: 12/08/2014, 19:21

Tài liệu cùng người dùng

Tài liệu liên quan