Java Programming for absolute beginner- P16 docx

20 189 0
Java Programming for absolute beginner- P16 docx

Đ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

The output for this application is shown in Figure 7.14. Within the itemState- Changed(ItemEvent) method, two string objects are built based on which event occurred. The getStateChange() method determines whether the item was selected or deselected by comparing the returned value to ItemEvent.SELECTED or ItemEvent.DESELECTED. The program then obtains the value of the item depend- ing on what type of component it is. The getItem() method in the ItemEvent class returns an Object object that represents the item that triggered the event. For the Checkbox and the Choice, this works out great because the object returned is a string that can be added to the "Event:" string. For the List, how- ever, I had to use the code: list.getItem(((Integer)e.getItem()).intValue()) 258 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 because e.getItem() returns the Integer index of the List item that was either selected or deselected. I had to explicitly cast it to an Integer object and call its intValue() method, which returns an int type value of the Integer object. Then I had to take that int value and pass it into list.getItem(int) so that I could get the String value of the List item. Table 7.8 lists some of the more common Ite- mEvent fields and methods. FIGURE 7.14 ItemEvents are triggered by Checkboxes, Choices, and Lists. Field or Method Description int DESELECTED Signifies that the ItemEvent occurred because an item was deselected. int SELECTED Signifies that the ItemEvent occurred because an item was selected. int getStateChange() Returns a value, either ItemEvent.DESELECTED or ItemEvent.SELECTED depending on what type of state change is associated with this ItemEvent. Object getItem() Returns an Object that represents the item whose state changed. TABLE 7.8 I TEM E VENT F IELDS AND M ETHODS JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 258 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Handling AdjustmentEvents The AdjustmentListener interface listens for AdjustmentEvents, which are trig- gered by objects that are adjustable, such as the Scrollbar component. Adjust- mentListener has only one method, adjustmentValueChanged(AdjustmentEvent), which is invoked when the value of an adjustable object is changed, as you can probably guess from the name of the method. The AdjustmentTest application tests this: /* * AdjustmentTest * Demonstrates the AdjustmentListener Interface on a scroll bar */ import java.awt.*; import java.awt.event.*; public class AdjustmentTest extends GUIFrame implements AdjustmentListener { Scrollbar bar; Label minimum, maximum, current; public AdjustmentTest() { super("AdjustmentListener Test"); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); int min = 0, max = 100, curr = 50; setLayout(gridbag); minimum = new Label(String.valueOf(min), Label.RIGHT); gridbag.setConstraints(minimum, constraints); add(minimum); bar = new Scrollbar(Scrollbar.HORIZONTAL, curr, 1, min, max + 1); constraints.ipadx = 200; gridbag.setConstraints(bar, constraints); bar.addAdjustmentListener(this); add(bar); maximum = new Label(String.valueOf(max)); constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.ipadx = 0; gridbag.setConstraints(maximum, constraints); add(maximum); current = new Label(String.valueOf(curr), Label.CENTER); gridbag.setConstraints(current, constraints); add(current); setSize(300, 150); setVisible(true); } 259 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 259 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. public static void main(String args[]) { new AdjustmentTest(); } public void adjustmentValueChanged(AdjustmentEvent e) { current.setText(String.valueOf(e.getValue())); } } This application is fairly straightforward. It creates a Scrollbar and some Labels that represent the Scrollbar’s minimum, maximum, and current values. The adjustmentValueChanged(AdjustmentEvent) method updates the current value of the Scrollbar by calling e.getValue(). You can see the output in Figure 7.15. Table 7.9 shows some useful fields and methods of the AdjustmentEvent class. 260 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 Field or Method Description int BLOCK_DECREMENT Block decrement adjustment type. int BLOCK_INCREMENT Block increment adjustment type. int TRACK Absolute tracking adjustment type. int UNIT_DECREMENT Unit decrement adjustment type. int UNIT_INCREMENT Unit increment adjustment type. int getAdjustmentType() Returns the int representation of the adjustment type. int getValue() Returns the int current value of the adjustable object. FIGURE 7.15 You use the Adjustment- Listener interface to determine when a Scrollbar value is being changed. TABLE 7.9 A DJUSTMENT E VENT F IELDS AND M ETHODS Handling TextEvents TextEvents are generated by high-level objects such as text components. The TextComponent class has the addTextListener(TextListener) method, and both TextField and TextArea are subclasses of TextComponent. The TextListener inter- face has only one method, textValueChanged(TextEvent). This method is JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 260 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. invoked any time the value of the text is changed, such as when text is added or deleted. The TextTest application implements the TextListener interface to copy what you are typing into a TextField. Here is the source code for TextTest.java: /* * TextTest * Demonstrates the TextListener interface */ import java.awt.*; import java.awt.event.*; public class TextTest extends GUIFrame implements TextListener { TextField text; TextField copyCat; public TextTest() { super("TextListener Test"); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); setLayout(gridbag); constraints.gridwidth = GridBagConstraints.REMAINDER; text = new TextField(25); gridbag.setConstraints(text, constraints); text.addTextListener(this); add(text); copyCat = new TextField(25); copyCat.setEnabled(false); gridbag.setConstraints(copyCat, constraints); add(copyCat); setSize(300, 150); setVisible(true); } public static void main(String args[]) { new TextTest(); } public void textValueChanged(TextEvent e) { copyCat.setText(text.getText()); } } This application simply creates two TextField objects, text and copyCat. text is the TextField that the user will be typing into. copyCat is a disabled TextField that will mimic the value of text each time its text value changes. You can see the TextListenerTest application in Figure 7.16. 261 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 261 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Handling MouseEvents Your computer’s mouse triggers MouseEvents. There are two types of mouse events. There are mouse motion events that are triggered by moving your mouse and regular mouse events that are triggered by clicking your mouse buttons or by moving your mouse into or out of a listener’s area. These two types of events have two listener classes: MouseListener, which listens for mouse button trig- gered events and entry and exit events, and MouseMotionListener, which listens for the motion (change in pointer location) of your mouse and also dragging (mouse moved while button is down) events. MouseInputListener of the javax.swing.event package, which is not covered in this book, is a subinterface of both MouseListener and MouseMotionListener, so you can implement MouseInputListener and add it using addMouseListener(MouseListener) or addMouseMotionListener(MouseMotionListener), or both, to listen to any of these types of MouseEvents. The MouseTest application implements both MouseListener and MouseMotion- Listener interfaces to capture MouseEvents. Here is the source code for MouseTest.java: /* * MouseTest * Demonstrates the MouseListener and MouseMotionListener interfaces */ import java.awt.*; import java.awt.event.*; public class MouseTest extends GUIFrame implements MouseListener, MouseMotionListener { Canvas canvas; Label location, event; public MouseTest() { super("Mouse Event Test"); canvas = new Canvas(); canvas.setBackground(Color.white); canvas.setSize(450, 450); TRICK 262 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 FIGURE 7.16 This application copies your text as you write it and displays it below. JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 262 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. canvas.addMouseListener(this); canvas.addMouseMotionListener(this); add(canvas, BorderLayout.CENTER); Panel infoPanel = new Panel(); infoPanel.setLayout(new GridLayout(0, 2, 10, 0)); location = new Label("Location:"); infoPanel.add(location); event = new Label("Event:"); infoPanel.add(event); add(infoPanel, BorderLayout.SOUTH); pack(); setVisible(true); } public static void main(String args[]) { new MouseTest(); } //The five MouseListener methods public void mouseClicked(MouseEvent me) { String text = "Event: Clicked Button "; switch(me.getModifiers()) { case (InputEvent.BUTTON1_MASK): text += "1"; break; case (InputEvent.BUTTON2_MASK): text += "2"; break; case (InputEvent.BUTTON3_MASK): text += "3"; break; default: text += "?"; } text += " (" + me.getClickCount() + "x)"; event.setText(text); } public void mouseEntered(MouseEvent me) { event.setText("Event: Entered"); } public void mouseExited(MouseEvent me) { event.setText("Event: Exited"); } public void mousePressed(MouseEvent me) { event.setText("Event: Pressed"); } 263 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 263 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. public void mouseReleased(MouseEvent me) { event.setText("Event: Released"); } //The two MouseMotionListener methods public void mouseMoved(MouseEvent me) { Point p = me.getPoint(); location.setText("Location: (" + p.x + ", " + p.y + ")"); } public void mouseDragged(MouseEvent me) { Point p = me.getPoint(); event.setText("Event: Dragged"); location.setText("Location: (" + p.x + ", " + p.y + ")"); } } The MouseTest object adds itself as a MouseListener and a MouseMotionListener to the Canvas, canvas. It overrides the listener methods to display on-screen the cur- rent location of the mouse cursor as well as the current event. MouseEvent meth- ods are summarized in Table 7.10, and MouseListener and MouseMotionListener methods are summarized in Table 7.11. I overrode the MouseListener methods as follows: The mouseClicked(MouseEvent) method updates the event Label as to which button was clicked by testing the value returned by getModifiers() against the static variables InputEvent.BUTTON1_MASK, InputEvent.BUTTON2_MASK, and InputEvent.BUTTON3_MASK. This method also counts the clicks for the events. A double-click, for example, will show up as (2x). This number is obtained by getting the getClickCount() method of the MouseEvent class, which returns an int value of the number of times the mouse button was successively clicked. The mouseEn- tered(MouseEvent) , mouseExited(MouseEvent), mousePressed(MouseEvent), and mouseReleased(MouseEvent) methods just update the event Label, indicating which event occurred. 264 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 Method Description int getClickCount() Returns the number of successive mouse clicks. Point getPoint() Returns a Point that represents the cursor location relative to the source component. int getX() Returns the horizontal portion of the location point. int getY() Returns the vertical portion of the location point. TABLE 7.10 M OUSE E VENT M ETHODS JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 264 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. I updated the MouseMotionListener method mouseMoved(MouseEvent) to update the current location of the mouse cursor, and the mouseDragged(MouseEvent) method to update the current event to indicate the mouse is being dragged and also to update the current location of the mouse cursor. Figure 7.17 shows the output where I double-clicked mouse button 1 at location (277, 151). The location returned by getLocation() is a Point object. The Point class maintains two pub- lic variables x and y, which represent a point. There are some methods associated with the class, but basically, for your purposes, it’s just that simple. Handling KeyEvents KeyEvents are triggered by keyboard actions performed by the users. The KeyLis- tener interface defines three methods, shown in Table 7.12. The addKeyLis- tener(KeyListener) method is defined in the Component class, so all components can process KeyEvents. The KeyEvent class has an insane number of static integers that represent each of the possible keys of different types of keyboards. There are 265 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 Method Listener Description void mouseClicked(MouseEvent) MouseListener Invoked when a mouse clicks (is pressed, and then released) on a component. void mouseEntered(MouseEvent) MouseListener Invoked when the mouse cursor enters the source component’s area. void mouseExited(MouseEvent) MouseListener Invoked when the mouse cursor exits the source component’s area. void mousePressed(MouseEvent) MouseListener Invoked when the mouse button is pressed down. void mouseReleased(MouseEvent) MouseListener Invoked when the mouse button is released. void mouseMoved(MouseEvent) MouseMotionListener Invoked when the mouse moves while within a component’s area. void mouseDragged(MouseEvent) MouseMotionListener Invoked when the mouse moves while the mouse button is down while within a component’s area. TABLE 7.11 M OUSE L ISTENER AND M OUSE M OTION L ISTENER M ETHODS JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 265 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. too many to list here. Refer to the JDK 1.3 documentation of the KeyEvent class for a full list. Basically, these constants start with the letters VK (which stand for virtual key codes) followed by an underscore and a string representation of the key. For instance, the keyboard keys are represented by the constants KeyEvent.VK_A through KeyEvent.VK_Z, and the arrow keys are KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_LEFT, and KeyEvent.VK_RIGHT. The more impor- tant KeyEvent methods are listed in Table 7.13. The keyTyped(KeyEvent) method is only invoked by keys that generate valid characters, such as alpha characters and numerical characters. Even the Esc key generates a valid character. Experiment with the KeyTest application and see which keys do and do not update the “Last Typed:” field. Another thing to note is that holding a key down can sometimes generate multiple key typed events without ever generating a key release event if a keyboard is enabled with auto-repeat. HINT 266 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 FIGURE 7.17 Listening to MouseEvents allows you to know what the user is doing with the mouse. Method Description void keyPressed(KeyEvent) Invoked when a key is pressed down. void keyReleased(KeyEvent) Invoked when a key is released. void keyTyped(KeyEvent) Invoked when a key is typed. TABLE 7.12 K EY L ISTENER M ETHODS JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 266 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The KeyTest application tests the handling of KeyEvents. Basically, it adds a KeyListener, which is itself, to a TextArea, textArea, and updates three labels with either pressed, released, or typed events. It gets the text representation of the key by first calling the getKeyCode() method of the KeyEvent class and pass- ing it into the getKeyText(int) method. In the keyPressed(KeyEvent) method, the lastPressed variable is displayed when the keyTyped(KeyEvent) method is called. This is done in the keyPressed(KeyEvent) method instead of in the key- Typed(KeyEvent) method because key typed events always return VK_UNDEFINED when getKeyCode() is called. Here is the source listing of KeyTest.java. Sample output is shown in Figure 7.18. /* * KeyTest * Demonstrates handling key events */ import java.awt.*; import java.awt.event.*; public class KeyTest extends GUIFrame implements KeyListener { TextArea textArea; Label pressed, released, typed; String lastPressedText; public KeyTest() { super("KeyListener Test"); textArea = new TextArea(10, 30); textArea.addKeyListener(this); add(textArea, BorderLayout.CENTER); Panel infoPanel = new Panel(); infoPanel.setLayout(new GridLayout(3, 0, 0, 10)); pressed = new Label("Last Pressed: <none>"); 267 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 Method Description char getKeyChar() Returns the character associated with the key. int getKeyCode() Returns an integer representation of the key. String getKeyModifiersText(int) Returns a String representation of the modifier keys such as Ctrl based on the given integer representation of the modifiers. String getKeyText(int) Returns a String representation of a key based on the given key code. TABLE 7.13 K EY E VENT M ETHODS JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 267 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... listing for MadInputPanel .java is as follows: Chapter 7 The MadInputPanel class is responsible for all user text input It has three Panels, which are laid out by the CardLayout layout manager Each Panel gets its own type of input One is for obtaining nouns, one is for obtaining verbs, and the last one is for obtaining all other types of words Each card has its own array of TextFields: nFields for nouns,... name—Nouns, Verbs, or Other JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 270 Java Programming for the Absolute Beginner 270 //Nouns nouns = new Panel(); nouns.setLayout(gridbag); addComponent(nouns, new Label("Enter some nouns:")); nFields = new TextField[8]; //put all noun fields in the second column constraints.gridx = 1; constraints.gridy = GridBagConstraints.RELATIVE; for (int n=0; n < nFields.length;... the text and redisplay the story as many times as you want Here is the source listing for AdvancedMadLib .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 2/25/03 8:53 AM Page 273 273 import java. awt.*; import java. awt.event.*; public AdvancedMadLib() { super("Create your own Song"); //Card Panel... TextArea story; Chapter 7 /* * AdvancedMadLib * A MadLib Application that demonstrates layout managers and events */ JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 274 Java Programming for the Absolute Beginner 274 showStory.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createStory(); storyDialog.setVisible(true); } }); navPanel.add(showStory); add(navPanel, BorderLayout.SOUTH);...JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 268 268 Java Programming for the Absolute Beginner infoPanel.add(pressed); released = new Label("Last Released: "); infoPanel.add(released); typed = new Label("Last Typed: "); infoPanel.add(typed);... addComponent(others, oFields[5]); constraints.gridwidth = 1; addComponent(others, new Label("Enter a location:")); addComponent(others, oFields[6]); add("Other", others); JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 272 Java Programming for the Absolute Beginner 272 v.add(oFields[4].getText()); v.add(vFields[3].getText()); v.add(nFields[4].getText()); v.add(vFields[3].getText()); v.add(nFields[6].getText());... left blank TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 277 8 C H A P T E R Writing Applets With the Internet as widely used as it is today, one of the more exciting features of Java is its use as a tool for Internet development You can embed Java right into a Web document... JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 269 269 Creating the MadInputPanel Class /* * MadInputPanel * The AdvancedMadLib game's input panel * All input is accepted here */ import java. awt.*; import java. awt.event.*; import java. util.Vector; public class MadInputPanel extends Panel { protected GridBagLayout gridbag; protected GridBagConstraints constraints; protected CardLayout cards; protected Panel... don't lay them out yet for (int o=0; o < oFields.length; o++) { oFields[o] = new TextField(20); } addComponent(others, oFields[0]); constraints.gridwidth = GridBagConstraints.REMAINDER; addComponent(others, oFields[1]); constraints.gridwidth = 1; 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... "\nDead-end ", " for a dead-end ", "\nDon't ", " to me oh ", "\nNow your ", " ", " on the ", "\nDon't ", " to me oh ", "\n\n", ", ", ", ", " my ", "\nDon't ", " a ", " ", "\n", ", ", ", ", " my ", "\nJust ", " your pretty ", "\nI'll be ", " you again \nI'll be ", " you in "}; String[] s = inputPanel.getStringArray(); for (int i = 0; i < segs.length; i++) { song += s[i] + segs[i]; } TEAM LinG - Live, Informative, . listing for MadInputPanel .java is as follows: /* * MadInputPanel * The AdvancedMadLib game's input panel. * All input is accepted here */ import java. awt.*; import java. awt.event.*; import java. util.Vector; public. MouseEvents. Here is the source code for MouseTest .java: /* * MouseTest * Demonstrates the MouseListener and MouseMotionListener interfaces */ import java. awt.*; import java. awt.event.*; public class. obtaining verbs, and the last one is for obtaining all other types of words. Each card has its own array of TextFields: nFields for nouns, vFields for verbs, and oFields for other fields. Each card lays

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