Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.

Similar presentations


Presentation on theme: "Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input."— Presentation transcript:

1 Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input

2 Event Listeners 2 If a class wants to respond to a user event under the Java event-handling system, it must implement the interface that deals with the events. These interfaces are called event listeners. The java.awt.event package contains the most useful listener interfaces as follows.  ActionListener—Action events, which are generated by a user taking an action on a component, such as a click on a button  AdjustmentListener—Adjustment events, which are generated when a component is adjusted, such as when a scrollbar is moved  FocusListener—Keyboard focus events, which are generated when a component such as a text field gains or loses the focus

3 Event Listeners 3  ItemListener—Item events, which are generated when an item such as a check box is changed  KeyListener—Keyboard events, which occur when a user enters text on the keyboard  MouseListener—Mouse events, which are generated by mouse clicks, a mouse entering a component’s area, and a mouse leaving a component’s area  MouseMotionListener—Mouse movement events, which track all movement by a mouse over a component  WindowListener—Window events, which are generated by a window being maximized, minimized, moved, or closed

4 Event Listeners 4 A class can implement as many listeners as needed. The following class is declared to handle both action and text events:  public class Suspense extends JFrame implements ActionListener, TextListener { //... } import java.awt.event.*;

5 Setting Up Components 5 After a component is created, you can call one of the following methods on the component to associate a listener with it:  addActionListener()—JButton, JCheckBox, JComboBox, JTextField, JRadioButton, and JMenuItem components  addFocusListener()—All Swing components  addItemListener()—JButton, JCheckBox, JComboBox, and JRadioButton components  addKeyListener()—All Swing components  addMouseListener()—All Swing components  addMouseMotionListener()—All Swing components

6 Setting Up Components 6  addTextListener()—JTextField and JTextArea components  addWindowListener()—JWindow and JFrame components The following example creates a JButton object and associates an action event listener with it:  JButton zap = new JButton(“Zap”); zap.addActionListener(this);

7 Event-Handling Methods 7 When you associate an interface with a class, the class must handle all the methods contained in the interface. In the case of event listeners, each of the methods is called automatically by the windowing system when the corresponding user event takes place. The ActionListener interface has only one method: actionPerformed(). All classes that implement ActionListener must have a method with the following structure:  public void actionPerformed(ActionEvent event) { // handle event here }

8 Event-Handling Methods 8 Every event-handling method is sent an event object of some kind. The object’s getSource() method can be used to determine the component that sent the event, as in the following example:  public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); } The object returned by the getSource() method can be compared with components by using the == operator. if (source == quitButton) { quitProgram(); } if (source == sortRecords) { sortRecords(); }

9 Event-Handling Methods 9 Many event-handling methods call a different method for each kind of event or component. This makes the event-handling method easier to read. In addition, if there is more than one event-handling method in a class, each one can call the same methods to get work done. The instanceof operator can be used in an event-handling method to determine what class of component generated the event. The following example can be used in a program with one button and one text field, each of which generates an action event:

10 Event-Handling Methods 10 void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source instanceof JTextField) { calculateScore(); } else if (source instanceof JButton) { quitProgram(); } }

11 Event-Handling Methods 11 import java.awt.event.*; import javax.swing.*; import java.awt.*; public class TitleChanger extends JFrame implements ActionListener { JButton b1 = new JButton(“Rosencrantz”); JButton b2 = new JButton(“Guildenstern”); public TitleChanger() { super(“Title Bar”); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); b1.addActionListener(this); b2.addActionListener(this); FlowLayout flow = new FlowLayout(); setLayout(flow);

12 Event-Handling Methods 12 add(b1); add(b2); pack(); setVisible(true); } public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source == b1) {setTitle(“Rosencrantz”);} else if (source == b2) {setTitle(“Guildenstern”);} repaint(); } public static void main(String[] arguments) { TitleChanger frame = new TitleChanger();} }

13 Event-Handling Methods 13

14 Working with Methods 14 Action Events Action events occur when a user completes an action using components such as buttons, check boxes, menu items, text fields, and radio buttons. A class must implement the ActionListener interface to handle these events. In addition, the addActionListener() method must be called on each component that should generate an action event—unless you want to ignore that component’s action events.

15 Working with Methods 15 The actionPerformed(ActionEvent) method is the only method of the ActionListener interface. It takes the following form: public void actionPerformed(ActionEvent event) { //... } In addition to the getSource() method, you can use the getActionCommand() method on the ActionEvent object to discover more information about the event’s source. Focus Events Focus events occur when any component gains or loses input focus on a graphical user interface. Focus describes the component that is active for keyboard input.

16 Working with Methods 16 A component can be given the focus by calling its requestFocus() method with no arguments, as in this example: JButton ok = new JButton(“OK”); ok.requestFocus(); To handle a focus event, a class must implement the FocusListener interface. Two methods are in the interface: focusGained(FocusEvent) and focusLost(FocusEvent). public void focusGained(FocusEvent event) {//...} public void focusLost(FocusEvent event) {//...}

17 Calculator.java 17 import java.awt.event.*; import javax.swing.*; import java.awt.*; public class Calculator extends JFrame implements FocusListener { JTextField value1 = new JTextField(“0”, 5); JLabel plus = new JLabel(“+”); JTextField value2 = new JTextField(“0”, 5); JLabel equals = new JLabel(“=”); JTextField sum = new JTextField(“0”, 5); public Calculator() { super(“Add Two Numbers”); setSize(350, 90); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

18 Calculator.java 18 FlowLayout flow = new FlowLayout(FlowLayout.CENTER); setLayout(flow); // add listeners value1.addFocusListener(this); value2.addFocusListener(this); // set up sum field sum.setEditable(false); // add components add(value1); add(plus); add(value2);

19 Calculator.java 19 add(equals); add(sum); setVisible(true); } public void focusGained(FocusEvent event) { try { float total = Float.parseFloat(value1.getText()) + Float.parseFloat(value2.getText()); sum.setText(“” + total); } catch (NumberFormatException nfe) { value1.setText(“0”); value2.setText(“0”); sum.setText(“0”); }

20 Calculator.java 20 public void focusLost(FocusEvent event) { focusGained(event); } public static void main(String[] arguments) { Calculator frame = new Calculator();} }

21 Item Events 21 Item events occur when an item is selected or deselected on components such as buttons, check boxes, or radio buttons. A class must implement the ItemListener interface to handle these events. The itemStateChanged(ItemEvent) method is the only method in the ItemListener interface. It takes the following form: void itemStateChanged(ItemEvent event) {//...} To determine in which item the event occurred, the getItem() method can be called on the ItemEvent object. You also can determine whether the item was selected or deselected by using the getStateChange() method. This method returns an integer that equals either the class variable ItemEvent.DESELECTED or ItemEvent.SELECTED.

22 FormatChooser.java 22 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FormatChooser extends JFrame implements ItemListener { String[] formats = { “(choose format)”, “Atom”, “RSS 0.92”, “RSS 1.0”, “RSS 2.0” }; String[] descriptions = { “Atom weblog and syndication format”, “RSS syndication format 0.92 (Netscape)”, “RSS/RDF syndication format 1.0 (RSS/RDF)”, “RSS syndication format 2.0 (UserLand)” };

23 FormatChooser.java 23 JComboBox formatBox = new JComboBox(); JLabel descriptionLabel = new JLabel(“”); public FormatChooser() { super(“Syndication Format”); setSize(420, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); for (int i = 0; i < formats.length; i++) { formatBox.addItem(formats[i]);} formatBox.addItemListener(this); add(BorderLayout.NORTH, formatBox); add(BorderLayout.CENTER, descriptionLabel); setVisible(true); }

24 FormatChooser.java 24 public void itemStateChanged(ItemEvent event) { int choice = formatBox.getSelectedIndex(); if (choice > 0) { descriptionLabel.setText(descriptions[choice-1]);} } public Insets getInsets() { return new Insets(50, 10, 10, 10); } public static void main(String[] arguments) { FormatChooser fc = new FormatChooser(); } }

25 FormatChooser.java 25

26 Key Events 26 Key events occur when a key is pressed on the keyboard. Any component can generate these events, and a class must implement the KeyListener interface to support them. There are three methods in the KeyListener interface: public void keyPressed(KeyEvent event) {//...} public void keyReleased(KeyEvent event) {//...} public void keyTyped(KeyEvent event) {//...} KeyEvent’s getKeyChar() method returns the character of the key associated with the event.

27 Mouse Events 27 Mouse events are generated by the following types of user interaction:  A mouse click  A mouse entering a component’s area  A mouse leaving a component’s area Any component can generate these events, which are implemented by a class through the MouseListener interface. This interface has five methods:  mouseClicked(MouseEvent)  mouseEntered(MouseEvent)  mouseExited(MouseEvent)  mousePressed(MouseEvent)  mouseReleased(MouseEvent)

28 Mouse Events 28 Each takes the same basic form as mouseReleased(MouseEvent): public void mouseReleased(MouseEvent event) {//...} The following methods can be used on MouseEvent objects: getClickCount()—Returns the number of times the mouse was clicked as an integer getPoint()—Returns the x,y coordinate within the component where the mouse was clicked as a Point object getX()—Returns the x position getY()—Returns the y position

29 Mouse Motion Events 29 Mouse motion events occur when a mouse is moved over a component. As with other mouse events, any component can generate mouse motion events. A class must implement the MouseMotionListener interface to support them. Two methods in the MouseMotionListener interface: public void mouseDragged(MouseEvent event) {//...} public void mouseMoved(MouseEvent event) {//...}

30 MousePrank.java 30 import java.awt.*; import java.awt.event.*; Import javax.swing.*; public class MousePrank extends JFrame implements ActionListener { public MousePrank() { super(“Message”); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(420, 220); BorderLayout border = new BorderLayout(); setLayout(border); JLabel message = new JLabel(“Click OK to close this program.”);

31 MousePrank.java 31 add(BorderLayout.NORTH, message); PrankPanel prank = new PrankPanel(); prank.ok.addActionListener(this); add(BorderLayout.CENTER, prank); setVisible(true); } public void actionPerformed(ActionEvent event) { System.exit(0); } public Insets getInsets() { return new Insets(40, 10, 10, 10);}

32 MousePrank.java 32 public static void main(String[] arguments) { new MousePrank(); } } class PrankPanel extends JPanel implements MouseMotionListener { JButton ok = new JButton(“OK”); int buttonX, buttonY, mouseX, mouseY; int width, height; PrankPanel() { super(); setLayout(null); addMouseMotionListener(this);

33 MousePrank.java 33 buttonX = 110; buttonY = 110; ok.setBounds(new Rectangle(buttonX, buttonY, 70, 20)); add(ok); } public void mouseMoved(MouseEvent event) { mouseX = event.getX(); mouseY = event.getY(); width = (int)getSize().getWidth(); height = (int)getSize().getHeight();

34 MousePrank.java 34 if (Math.abs((mouseX + 35) - buttonX) < 50) { buttonX = moveButton(mouseX, buttonX, width); repaint(); } if (Math.abs((mouseY + 10) - buttonY) < 50) { buttonY = moveButton(mouseY, buttonY, height); repaint(); } } public void mouseDragged(MouseEvent event) { // ignore this event }

35 MousePrank.java 35 private int moveButton(int mouseAt, int buttonAt, int border) { if (buttonAt < mouseAt) { buttonAt—;} else { buttonAt++; } if (buttonAt > (border - 20)) {buttonAt = 10;} if (buttonAt < 0) { buttonAt = border - 80; } return buttonAt; } public void paintComponent(Graphics comp) { super.paintComponent(comp); ok.setBounds(buttonX, buttonY, 70, 20); }

36 MousePrank.java 36


Download ppt "Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input."

Similar presentations


Ads by Google