Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

Similar presentations


Presentation on theme: "CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost."— Presentation transcript:

1 CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost

2 2 Lecture Outline Event Handling  Mostly in the context of GUIs  Mouse interaction  Keyboard interaction  Window interaction Inner Classes  Static inner classes  Member classes  Local classes  Anonymous inner classes

3 3 Events, Event Sources, and Event Listeners User interface events include key presses, mouse moves, button clicks, and so on Most programs don't want to be flooded by event notifications  Subscribe only to events we are interested in A program can indicate that it only cares about certain specific events

4 4 Events, Event Sources, and Event Listeners Event listener:  Notified when event happens  Belongs to a class that is provided by the application programmer  Its methods describe the actions to be taken when an event occurs  A program indicates which events it needs to receive by creating and registering event listener objects Event source:  … the thing that generates the event  When an event occurs, the event source notifies all event listeners

5 5 Events, Event Sources, and Event Listeners Example: Use JButton components for buttons; attach an ActionListener to each button ActionListener interface: Need to supply a class whose actionPerformed method contains instructions to be executed when button is clicked public interface ActionListener { void actionPerformed(ActionEvent event); }

6 6 Events, Event Sources, and Event Listeners event parameter contains details about the event, such as the time at which it occurred  Different types of events hold different information (mouse, key, action, scroll, etc.) Construct an object of the listener and add it to the button: // Code example ActionListener listener = new ClickListener(); button.addActionListener(listener);

7 7 File ClickListener.java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** An action listener that prints a message. */ public class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event){ System.out.println("I was clicked."); } }

8 8 File ButtonTester.java import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; /** This program demonstrates how to install an action listener. */ public class ButtonTester { public static void main(String[] args) { JFrame frame = new JFrame(); JButton button = new JButton("Click me!"); frame.add(button);

9 9 File ClickListener.java ActionListener listener = new ClickListener(); button.addActionListener(listener); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } private static final int FRAME_WIDTH = 100; private static final int FRAME_HEIGHT = 60; }

10 10 File ClickListener.java Output:

11 11 Mouse Events Use a MouseListener to capture mouse events Implement the MouseListener interface: public interface MouseListener { void mousePressed(MouseEvent event); // Called when a mouse button has been pressed on a component void mouseReleased(MouseEvent event); // Called when a mouse button has been released on a component void mouseClicked(MouseEvent event); // Called when the mouse has been clicked on a component void mouseEntered(MouseEvent event); // Called when the mouse enters a component void mouseExited(MouseEvent event); // Called when the mouse exits a component }

12 12 Mouse Events mousePressed, mouseReleased : called when a mouse button is pressed or released mouseClicked : if button is pressed and released in quick succession, and mouse hasn't moved mouseEntered, mouseExited : mouse has entered or exited the component's area

13 13 Mouse Events Add a mouse listener to a component by calling the addMouseListener method: We can add a MouseListener to any Component in our GUI // Code Example public class MyMouseListener implements MouseListener { // Implements five required methods } MouseListener listener = new MyMouseListener(); component.addMouseListener(listener);

14 14 Mouse Events class MousePressListener implements MouseListener { public void mousePressed(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x, y); } // Do-nothing methods public void mouseReleased(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} } All methods of the interface must be implemented (Undesired methods may be left empty)

15 15 Window Listeners Generate events when some aspect of a graphical window changes  By default, window behaviors are not implemented Why is one interested in window events?  Useful to implement your shut down protocol Maybe save some stuff to disk, etc.  Stop your program from running

16 16 WindowListener interface windowActivated (WindowEvent e) windowActivated windowClosed (WindowEvent e) windowClosed windowClosing (WindowEvent e) windowClosing windowDeactivated (WindowEvent e) windowDeactivated windowDeiconified (WindowEvent e) windowDeiconified windowIconified (WindowEvent e) windowIconified windowOpened (WindowEvent e) windowOpened

17 17 Some shortcuts are available JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Adapter classes  Saves you from writing empty method stubs for events you don’t want to monitor java.awt.event.MouseAdapter java.awt.event.KeyAdapter java.awt.event.WindowAdapter // Code Examples

18 18 Inner classes Sometimes we define a class whose purpose is only to "help out" another class.  E.g. Iterator or Node within LinkedList In some situations, it is nice if the helper class didn't stand on its own, but instead was more closely associated with the parent class itself.

19 19 Inner classes So far, all classes we have defined have been “top level” classes.  as far as the Java compiler is concerned, the classes are independent and exist on there own. We can do some things to group classes  Put classes in the same file  Packages These are useful but do not imply (or allow) a very close association  Use Inner Classes

20 20 Types of Inner Classes Nested top-level class Member class Local class Anonymous class Let us look at each one in more detail

21 21 Example public class Animation extends Component { public Animation(....){... addMouseListener( new AnimationRequestHandler() );... } public void beginAnimation() { // To be called when component is clicked... }

22 22 Nested Top Level Class This is a class defined as a static class member.  It’s still really a top-level class, but from outside its name is prefixed with the name of the containing class separated by a dot: Access to the class can be controlled through protection modifiers. LinkedList.Node node;

23 23 Example public class Animation extends Component{ public Animation(....){... addMouseListener( new AnimationRequestHandler() );.... } public void beginAnimation() {... } private static class AnimationRequestHandler extends MouseAdapter{ public void mouseClicked (MouseEvent e){ Animation anim = (Animation)e.getSource(); anim.beginAnimation(); }

24 24 Example beginAnimation() must be public because  AnimationRequestHandler is a top level class and has no special access to methods in Animation,  The inner class AnimationRequestHandler can access only public methods and public instance variables of the Animation class (like any other class), not private ones. Just like with any other method, you must use objectName.methodName() notation for beginAnimation().

25 25 Member Classes These are not top level classes  They are declared inside the class body like instance variables and methods (not static)  Each instance of a member class has a corresponding instance of the containing class (an implicit link to an instance of its parent class - usually the instance that created it)  Instances of member classes have access to the instance variables and methods of the containing class (and vice versa), as well as other member class instance variables and methods created by the original class.

26 26 Example public class Animation extends Component { public Animation(....){... addMouseListener( new AnimationRequestHandler() );... } void beginAnimation () {... } private class AnimationRequestHandler extends MouseAdapter { public void mouseClicked(MouseEvent e){ beginAnimation(); }

27 27 Example beginAnimation() does not need to be public because AnimationRequestHandler is member class and has access to methods in Animation  the member class AnimationRequestHandler can access any method or instance variable of the Animation class. This time beginAnimation() can be called without a source because there is only one object it could belong to. Technical Note: Member classes can't contain any static members and they can't have the same name as any containing class or package.

28 28 Local Classes These are similar to member classes  The have access to all class members Local classes are different than member classes in that  They are declared within a method or constructor  They also have access to final local variables within the scope in which they are declared  They are only visible and usable within the scope of their containing method / constructor Local classes have the same restrictions as member classes:  local classes can't contain any static members and they can't have the same name as any containing class or package.

29 29 Example public class Animation extends Component { public Animation(....){ class AnimationRequestHandler extends MouseAdapter{ public void mouseClicked(MouseEvent e){ beginAnimation(); }... addMouseListener( new AnimationRequestHandler() );... } void beginAnimation () {... }

30 30 Anonymous Inner Classes These are similar to local classes, except they have no names. Instead, they are defined within the expression that instantiates them. Anonymous classes must either extend a class, or implement an interface (and extend Object)  Why? We need some named way to access a defined API.

31 31 Example public class Animation extends Component { public Animation(....){... addMouseListener( new MouseAdapter(){ public void mouseClicked(MouseEvent e){ beginAnimation(); } });... } void beginAnimation () {... }

32 32 Notes on Anonymous Classes MouseAdapter is the name of the class being extended or interface being implemented. Any parameters to the constructer for MouseAdapter need to be included. An anonymous class inherits its constructor because it is never given the chance to define its own. An anonymous class has no name. An anonymous class has no protection modifiers - it has no name, so you can't access it from outside anyway.

33 33 Inner Classes as Listeners Example: investment viewer program; whenever button is clicked, interest is added, and new balance is displayed

34 34 Processing Text Input Use JTextField components to provide space for user input Place a JLabel next to each text field Supply a button that the user can press to indicate that the input is ready for processing int FIELD_WIDTH = 10; // In characters JTextField rateField = new JTextField(FIELD_WIDTH); JLabel rateLabel = new JLabel(“Interest Rate: ");

35 35 Processing Text Input The button's actionPerformed method reads the user input from the text fields (use getText ) class AddInterestListener implements ActionListener { public void actionPerformed (ActionEvent event) { double rate = Double.parseDouble(rateField.getText());... } }

36 36 Conclusion Questions? In Lab Now


Download ppt "CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost."

Similar presentations


Ads by Google