Java Programming for absolute beginner- P15 potx

20 285 0
Java Programming for absolute beginner- P15 potx

Đ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

First off, it extends Frame, so it is a Frame. It sets its background color to System- Color.control , which as you might remember from the previous chapter, is the color that your operating system uses for painting windows. Then it adds a Win- dowAdapter object as its WindowListener. Pay close attention to the syntax here. This is actually an inner-class declaration, which you’ll learn about later on in this chapter. Another cool thing it does is center itself, no matter what size it is when it becomes visible. I did this by overriding the setVisible(boolean) method. If the argument passed in is true, I get the screen size by calling Toolkit.getDefault- Toolkit().getScreenSize() , which returns a Dimension object representing the resolution of the computer screen, whether it is 640 by 480, 800 by 600, or what- ever. The Toolkit class is the abstract subclass of all implementations of the AWT, the default of which is different depending on what operating system you are running. To center the GUIFrame on screen I needed to know the screen size and the size of the GUIFrame. The position of the GUIFrame is set with the setLoca- tion(int, int) method, where the first int is the x location and the second int is the y location. The center location is half the difference of the screen width minus the GUIFrame width as the x position, and half the difference of the screen height minus the GUIFrame height as the y position. super.setVisible(visible) is called so that the corresponding method in the Frame class can take care of actually making the GUIFrame visible. Take a look at Figure 7.7 to see what the GUIFrame looks like. Here is a test of the GUIFrame class, GUIFrameTest: /* * GUIFrameTest * Demonstrates the GUIFrame Class */ public class GUIFrameTest { public static void main(String args[]) { GUIFrame frame = new GUIFrame("GUIFrame Test"); frame.setSize(400, 300); frame.setVisible(true); } } Using CardLayout The CardLayout layout manager lays out its components as cards. You can think of each card as a card within a deck of playing cards. To make this analogy work, imagine that the cards are face up and only the top card is visible. You can take a card off the top of the deck and add it to the bottom to make the next card vis- ible. Each card is actually a Java component. Only one of the components is visi- 238 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 238 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ble at a time. The first component added to the layout is visible when the con- tainer is initially visible. CardLayout has some methods that change which com- ponent is visible, as you can see in Table 7.5. When adding components to a CardLayout, you specify a string. That string is used as an identifier so that you can flip directly to that card when necessary. The name of the class is pretty self- explanatory. You can think of it as a deck of cards or a deck of components that 239 C h a p t e r 7 A d v a n c e d G U I : L a y o u t M a n a g e r s a n d E v e n t H a n d l i n g FIGURE 7.7 The GUIFrame class tested here is used throughout this chapter. Method Description CardLayout() Constructs a CardLayout object with no horizontal or vertical gaps. CardLayout(int, int) Constructs a CardLayout object with the given horizontal and vertical gaps. void first(Container) Displays the first card of the given Container object. void last(Container) Displays the last card of the given Container object. void next(Container) Displays the next card of the given Container object. void previous(Container) Displays the previous card of the given Container object. void show(String, Container) Displays the card that was added to this Container using the specified String identifier. TABLE 7.5 C ARD L AYOUT M ETHODS JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 239 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. can be traversed through, or dealt, one at a time. The CardLayoutTest application is an example: /* * CardLayoutTest * Demonstrates the CardLayout layout manager */ import java.awt.*; import java.awt.event.*; public class CardLayoutTest extends GUIFrame implements ActionListener { Panel cardPanel; Panel buttonPanel; Button nextButton; Button prevButton; Label l1, l2, l3; TextArea ta; CardLayout cardLayout; public CardLayoutTest() { super("CardLayout Test"); cardLayout = new CardLayout(); cardPanel = new Panel(); cardPanel.setLayout(cardLayout); cardPanel.setBackground(Color.black); cardPanel.setForeground(Color.yellow); Font lFont = new Font("Verdana", Font.BOLD, 20); l1 = new Label("First", Label.LEFT); l1.setFont(lFont); l2 = new Label("Second", Label.CENTER); l2.setFont(lFont); ta = new TextArea("You can put any Components" + "\nthat you want, or even add a Container" + "\nthat itself contains multiple Components", 4, 35); ta.setForeground(Color.black); l3 = new Label("Last", Label.RIGHT); l3.setFont(lFont); cardPanel.add("C1", l1); cardPanel.add("C2", l2); cardPanel.add("C3", ta); cardPanel.add("C4", l3); add(cardPanel, BorderLayout.CENTER); buttonPanel = new Panel(); prevButton = new Button("Previous"); prevButton.addActionListener(this); buttonPanel.add(prevButton); nextButton = new Button("Next"); nextButton.addActionListener(this); buttonPanel.add(nextButton); add(buttonPanel, BorderLayout.SOUTH); 240 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 240 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. //pack sets the minimum size able to display the largest //Dimension Components pack(); setVisible(true); } public static void main(String args[]) { CardLayoutTest clt = new CardLayoutTest(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == nextButton) cardLayout.next(cardPanel); else cardLayout.previous(cardPanel); } } CardLayoutTest extends GUIFrame, which itself has a BorderLayout by default, but contains a Panel, cardPanel, which has its layout set to cardLayout, a Card- Layout object. cardLayout lays out three labels: l1, l2, and l3, and a TextArea, ta, inside of cardPanel. The order that these are added is as follows: cardPanel.add("C1", l1); cardPanel.add("C2", l2); cardPanel.add("C3", ta); cardPanel.add("C4", l3); Remember that the components are added along with a String identifier, which can call up any one of the cards to the front. After these four components are added to cardPanel, cardPanel is added to the GUIFrame at BorderLayout.CENTER. prevButton and nextButton are Button objects that I added to another Panel, buttonPanel, which in turn, I added to the GUIFrame at BorderLayout.SOUTH. Some event handling is required with these Buttons, covered in the next section. Basically prevButton causes cardLayout.previous(cardPanel) to be called and nextButton causes cardLayout.next(cardPanel) to be called when they are clicked. The output is shown in Figure 7.8. 241 C h a p t e r 7 A d v a n c e d G U I : L a y o u t M a n a g e r s a n d E v e n t H a n d l i n g FIGURE 7.8 The CardLayout manager displays its components one at a time. JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 241 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Handling AWT Events Up to this point, you’ve learned how to create components and lay them out within a container. However, you haven’t had much use for these components yet. You were exposed to a bit of event handling already. This section concen- trates on the java.awt.event package, which has classes that are used for handling events caused by user interaction with the AWT GUI interfaces you cre- ate. In this section, you’ll learn about WindowEvents, ActionEvents, FocusEvents, ItemEvents, AdjustmentEvents, TextEvents, MouseEvents, and KeyEvents. The classes that you need to use to handle AWT events are in the java.awt.event package, so don’t forget to import it into your applications. All the Event classes explored here directly extend the abstract AWTEvent class or the ComponentEvent class, which itself is a direct subclass of AWTEvent. AWTEvent is a subclass of the EventObject class. KeyEvent and MouseEvent extend InputEvent, which is a sub- class of ComponentEvent. You handle AWT events in Java (1.1 and higher) by implementing a listener inter- face that “listens” for events that can be triggered by components. A component that triggers events must register the listeners so that the listeners can “hear” the component’s events. A component keeps a list of listeners that it informs when it triggers an event by calling one of its required methods. For example, you already know that to be a WindowListener, a class must implement all six of the Win- dowListener interfaces. When a WindowEvent occurs, the window will inform its listeners by calling one of those six methods, depending on which event has occurred. This will become more intuitive to you the more you do it, and because no GUI is useful without event handling, you will be using it every time you cre- ate one. Handling WindowEvents You’ve already implemented the WindowListener interface in the previous chap- ter and also in this chapter. Now you will learn about handling WindowEvents in more detail. To handle WindowEvents, you need to implement the WindowListener interface. When you implement the WindowListener interface or any other abstract interface, you need to implement its methods, which are listed in Table 7.6. These methods are called when corresponding actions have taken place. For WindowListeners, when a window is opened, closed, activated, deactivated, iconi- fied (minimized), or deiconified (restored), the corresponding method is called to notify the interested “listener” class that the action has taken place. The WindowEventTest application is a test of the WindowListener interface. It extends GUIFrame and implements WindowListener. The window opens and the events are handled simply by printing to standard output the event that has 242 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 242 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 243 C h a p t e r 7 A d v a n c e d G U I : L a y o u t M a n a g e r s a n d E v e n t H a n d l i n g taken place, so as you perform actions on the window that pops up, pay attention to the standard output so you can know when each method is called. Here is the source code for WindowEventTest.java: /* * WindowEventTest * Tests WindowEvents */ import java.awt.*; import java.awt.event.*; public class WindowEventTest implements WindowListener { public WindowEventTest() { Frame frame = new Frame("WindowEvent Test"); frame.add(new Label("See Command Prompt output for event log ")); frame.addWindowListener(this); frame.pack(); frame.setVisible(true); } public static void main(String args[]) { WindowEventTest wet = new WindowEventTest(); } //WindowListener Interface public void windowClosing(WindowEvent e) { Method Description void windowActivated(WindowEvent) Called when a window becomes active (able to accept input events). void windowClosed(WindowEvent) Called when a window is closed (disposed). void windowClosing(WindowEvent) Called when a user attempts to close a window. You implement this method to conditionally close the window. void windowDeactivated(WindowEvent) Called when a window is deactivated (loses input focus). void windowDeiconified(WindowEvent) Called when a window is restored from a minimized state. void windowIconified(WindowEvent) Called when a window becomes minimized. void windowOpened(WindowEvent) Called when a window initially becomes visible. TABLE 7.6 W INDOW L ISTENER M ETHODS JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 243 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. System.out.println("windowClosing"); ((Window)e.getSource()).dispose(); } public void windowOpened(WindowEvent e) { System.out.println("windowOpened"); } public void windowActivated(WindowEvent e) { System.out.println("windowActivated"); } public void windowDeactivated(WindowEvent e) { System.out.println("windowDeactivated"); } public void windowIconified(WindowEvent e) { System.out.println("windowIconified"); } public void windowDeiconified(WindowEvent e) { System.out.println("windowDeiconified"); } public void windowClosed(WindowEvent e) { System.out.println("windowClosed"); System.exit(0); } } Most of the code here should be familiar. You’ve already used the methods of the WindowListener interface before, except that before now, you implemented them except for windowClosing(WindowEvent) as empty do-nothing methods. Previ- ously, you had always called System.exit(0) in the windowClosing(WindowEvent) method. In this program, you wanted to see the windowClosed(WindowEvent) method triggered, so instead, you called: ((Window)e.getSource()).dispose(); As you learned in the previous chapter, the dispose() method releases all native resources used for the window and its subcomponents and closes the window. You can make the window displayable again, though, assuming System.exit(0) isn’t called (which it is here) by calling pack() or show(). The getSource() method of the WindowEvent class, inherited from EventObject, is discussed in the next section. Basically, e.getSource() returns the object that initiated this Win- dowEvent , which in this case will always be the WindowEventTest object. In the windowClosed(WindowEvent) method, I called System.exit(0) to exit the Java VM after the window is closed. The windowClosed(WindowEvent) method is triggered when the dispose() method is called, closing the window. The WindowEventTest class implements the WindowListener interface, so it becomes WindowListener itself, which is better than a window watcher, like the lady that lives across the street from me and calls the police if I forget about a 244 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 244 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. holiday and bring my garbage out on the wrong day. Anyway, WindowEventTest is also a Frame because it extends Frame. It is the Frame and the WindowListener that listens to itself. It registers itself as a listener by calling the addWindowLis- tener(WindowListener) method and passing itself as an argument by using the this keyword. Because of this, when a WindowEvent is triggered, it will call one of its own WindowListener methods so that it can handle its own events. This is not the only way to do it, though. It can register any WindowListener, or even multi- ple listeners, also by calling the addWindowListener(WindowListener) method for each of them. You can see the output of this application in Figure 7.9. When I started the appli- cation, using the command: java WindowEventTest 245 C h a p t e r 7 A d v a n c e d G U I : L a y o u t M a n a g e r s a n d E v e n t H a n d l i n g FIGURE 7.9 The WindowEventTest application shows how to capture WindowEvents. It ran the first two lines of output, windowActivated and windowOpened. After that, I minimized the window, running the next two lines, windowIconified and windowDeactivated. Then I restored the window (using Windows by clicking the icon on the taskbar), which triggered three events. These events— windowActi- vated , windowDeiconified, and windowActivated—generated the output, indicat- ing that I activated the window by initially interacting with it on the taskbar. As the window was restored, the window triggered the windowDeiconified(Window- Event) method; finally, the window was activated again. When I closed the window by clicking the close button (the x), the windowClos- ing and windowClosed lines printed in the output. JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 245 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Using Inner Adapter Classes You’re probably thinking, yeah, okay, Joe, what about that funky code in GUIFrame.java that closes the window? It doesn’t implement WindowListener, nor does it define its methods, like you just told me I have to do, right? Well, actu- ally it does, indirectly. The WindowAdapter class implements the WindowListener interface and defines the methods as empty do-nothing methods. The sole purpose of the Win- dowAdapter class and other adapter classes, such as FocusAdapter, KeyAdapter, MouseAdapter, and MouseMotionAdapter, is to facilitate the implementation of their respective listener interfaces. Because they are classes that implement the listener’s methods as do-nothing methods, you don’t have to implement them all. You only need to implement the ones that you are interested in. In the GUIFrame class, you add the WindowListener as follows: addWindowListener(new WindowAdapter() { //only need to override the method needed public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } }); The code is even more confusing because the windowClosing(WindowEvent) method is overridden right within the call to the addWindowListener(WindowLis- tener) method. The declaration of the WindowAdapter here is called an anonymous inner class. Here, I am creating a subclass of WindowAdapter and overriding its win- dowClosing(WindowEvent) method without actually giving that subclass a name and I am doing this within another class’s definition. That’s why it’s called an anonymous inner class. Take a look at the files in the directory where you com- piled GUIFrame.java. You will see a file named GUIFrame$1.class. This file holds 246 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r INTHEREAL WORLD In the real world, the windowClosing(WindowEvent) method tells you when a user attempts to exit your GUI program. As you saw in Chapter 6, you don’t have to close the window when a user wants to close it (remember UselessFrame?). This allows programmers to catch the window-closing event, so they can perform whatever cleanup is necessary. It also is a safeguard against bad data. A pro- grammer can store the changes made to the data while the window was opened before actually exiting the system, or perhaps, prompt the user: “Are you sure you want me to go away, sniff?” It’s good to know when a user wants to exit the program for reasons such as these. JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 246 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. the class definition of the anonymous WindowAdapter subclass. The syntax for cre- ating an anonymous inner class is as follows: OuterClass { new InnerClassName(constructor_arguments) { subclass_definition; } } Inner classes are Java classes that are defined within the curly braces of another class. An inner class has access to the outer classes’ members and methods. For now, this is all you need to know about inner classes. You will revisit this topic in Chapter 11, “Custom Event Handling and File I/O.” Handling ActionEvents ActionEvents are high-level events that are triggered by a component when it generates an event, such as a clicked Button. ActionEvents are listened to by implementing the ActionListener interface. This interface defines only one method actionPerformed(ActionEvent). Take a look at ButtonEventTest.java, which implements the ActionListener interface: /* * ButtonEventTest * Demonstrates using ActionListener to handle Button * events by counting the number of times a button is clicked. */ import java.awt.*; import java.awt.event.*; public class ButtonEventTest extends GUIFrame implements ActionListener { Button button; int count; Label clicksLabel; public ButtonEventTest() { super("Button Event Test"); button = new Button("Button"); button.addActionListener(this); add(button, BorderLayout.CENTER); count = 0; clicksLabel = new Label(); updateLabel(); add(clicksLabel, BorderLayout.SOUTH); setSize(200, 200); setVisible(true); } 247 C h a p t e r 7 A d v a n c e d G U I : L a y o u t M a n a g e r s a n d E v e n t H a n d l i n g JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 247 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]...JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 248 Java Programming for the Absolute Beginner 248 public static void main(String args[]) { new ButtonEventTest(); } private void updateLabel() { String text = "Number of times clicked: "; clicksLabel.setText(text + String.valueOf(count)); } public void actionPerformed(ActionEvent e) { count++; updateLabel();... Button("Button 2"); button2.addActionListener(this); TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Advanced GUI: Layout Managers and Event Handling Description Chapter 7 Field or Method JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 250 250 Java Programming for the Absolute Beginner //set the action command button2.setActionCommand("Increment... Button is an object All objects in Java inherit from the Object class, but the Object class doesn’t inherit from any other class Because you know here that you can only expect a Button, you can cast the Object object to a Button object so you can call its methods that are defined in the Button class JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 252 252 Java Programming for the Absolute Beginner More ActionEvent... LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Advanced GUI: Layout Managers and Event Handling textField = new TextField("Track 1", 15); textField.addFocusListener(this); add(textField); Chapter 7 TextField textField; Checkbox checkBox; JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 256 Java Programming for the Absolute Beginner... list.add("Breakfast"); list.add("Brunch"); list.add("Lunch"); list.add("Snack"); list.add("Dinner"); list.add("Dessert"); list.addActionListener(this); controlPanel.add(list); JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 254 Java Programming for the Absolute Beginner 254 else if (e.getSource() == textField) { whoDoneItTextField.setText("A TextField"); } else if (e.getSource() == button) { whoDoneItTextField.setText("A... call the actionPerformed(ActionEvent) method If the two buttons perform different actions, you need to determine the source of the ActionEvent and conditionally execute code based on which button triggered it Here is a listing of ActionEventSourceTest .java: TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-07.qxd... allow for a selection of items, such as Checkbox, Choice, and List The ItemListener interface listens for these events It contains only one method, itemStateChanged(ItemEvent) It is called when an item is either selected or deselected The ItemTest application tests the ItemListener interface Here is the source code for ItemTest .java: /* * ItemTest * Demonstrates the ItemListener interface */ import java. awt.*;... code: /* * FocusTest * Demonstrates listening to focus events */ import java. awt.*; import java. awt.event.*; public class FocusTest extends GUIFrame implements FocusListener { Label label; Button button; TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 255 255 public FocusTest()... relevant to this section happens in the actionPerformed(ActionEvent) method In this method, you see the getSource() method again This method is inherited from the EventObject class, so all classes that subclass EventObject have this TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 251... and displays the action command that’s associated with the component’s ActionEvent If you don’t explicitly set the action command for the button, the button’s label will be the action command The action command for a TextField is the text it contains The action command for a List is the text of the item To get a TextField to trigger an ActionEvent, press the Enter key while it has your input focus . the ItemListener interface. Here is the source code for ItemTest .java: /* * ItemTest * Demonstrates the ItemListener interface */ import java. awt.*; import java. awt.event.*; public class ItemTest extends. so as you perform actions on the window that pops up, pay attention to the standard output so you can know when each method is called. Here is the source code for WindowEventTest .java: /* * WindowEventTest *. You’ve already used the methods of the WindowListener interface before, except that before now, you implemented them except for windowClosing(WindowEvent) as empty do-nothing methods. Previ- ously,

Ngày đăng: 03/07/2014, 05:20

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

Tài liệu liên quan