Published on

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. om JDK 1.1 AWT Event Handling .c ===================== DF aP vi n ee w.ww Object Computing, Inc. 1 AWT Event Handling
  2. 2. om AWT .c DF • Abstract Windowing Toolkit package – java.awt aP • Easier to learn than Motif/X and MFC • Not as easy as using graphical GUI vi builders – several companies are creating them for Java ee – will output Java code that uses the AWT package • AWT classes fall in four categories – components n – containers w. – layout managers – event handlingww Object Computing, Inc. 2 AWT Event Handling
  3. 3. om Steps To Use AWT .c • Create a container – Frame, Dialog, Window, Panel, ScrollPane DF • Select a LayoutManager – Flow, Border, Grid, GridBag, Card, none (null) • Create components aP – Button, Checkbox, Choice, Label, List, TextArea, TextField, PopupMenu • Add components to container vi • Specify event handling (changed in 1.1) ee – listeners are objects interested in events – sources are objects that “fire” events – register listeners with sources n • component.add<EventType>Listener – EventTypes are ActionEvent, AdjustmentEvent, w. ComponentEvent, FocusEvent, ItemEvent, KeyEvent, MouseEvent, TextEvent, WindowEvent – implement methods of listener interfaces in listener classesww • an event object is passed to the methods • ActionListener, AdjustmentListener, ComponentListener, FocusListener, ItemListener, KeyListener, MouseListener, MouseMotionListener, TextListener, WindowListener Object Computing, Inc. 3 AWT Event Handling
  4. 4. om Event Sources, .c Listeners, and Objects DF Event Object • describes an event • ex. ActionEvent holds state of Shift key tes crea aP Event Source vi • generates events • ex. Button pas ses to ee list ene rm eth od Event Listener • any object can implement these interfaces • ex. ActionListener has method actionPerformed() n w.ww Object Computing, Inc. 4 AWT Event Handling
  5. 5. om Simple AWT Example .c DF import java.awt.*; import java.awt.event.*; private private aP public class SimpleAWT extends java.applet.Applet implements ActionListener, ItemListener { Button button = new Button("Push Me!"); Checkbox checkbox = new Checkbox("Check Me!"); private Choice choice = new Choice(); vi private Label label = new Label("Pick something!"); public void init() { button.addActionListener(this); ee checkbox.addItemListener(this); choice.addItemListener(this); // An Applet is a Container because it extends Panel. setLayout(new BorderLayout()); n choice.addItem("Red"); w. choice.addItem("Green"); choice.addItem("Blue"); Panel panel = new Panel(); panel.add(button);ww panel.add(checkbox); panel.add(choice); add(label, "Center"); add(panel, "South"); } Object Computing, Inc. 5 AWT Event Handling
  6. 6. om Simple AWT Example .c (Cont’d) DF public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { label.setText("The Button was pushed."); } } aP public void itemStateChanged(ItemEvent e) { if (e.getSource() == checkbox) { label.setText("The Checkbox is now " + vi checkbox.getState() + "."); } else if (e.getSource() == choice) { label.setText(choice.getSelectedItem() + “ was selected.”); } ee } } n w.ww Object Computing, Inc. 6 AWT Event Handling
  7. 7. om Event Classes .c DF • Hierarchy java.util.EventObject – java.awt.AWTEvent aP • java.awt.event.ComponentEvent – java.awt.event.FocusEvent vi – java.awt.event.InputEvent • java.awt.event.KeyEvent • java.awt.event.MouseEvent ee • java.awt.event.ActionEvent • java.awt.event.AdjustmentEvent • java.awt.event.ItemEvent • java.awt.event.TextEvent n • Can create custom, non-AWT event w. classes – extend java.util.EventObjectww Object Computing, Inc. 7 AWT Event Handling
  8. 8. om Event Object Contents .c DF • java.util.EventObject – source holds a reference to the object that fired the event – java.awt.AWTEvent • id indicates event type aP – set to a constant in specific event classes (listed on following pages) • java.awt.event.ActionEvent – modifiers indicates state of control, shift, and meta (alt) vi keys – actionCommand holds the action specific command string ee • usually the label of a Button or MenuItem • java.awt.event.AdjustmentEvent – for Scrollbars used for n – value holds value checkboxes and – adjustmentType is unit +/-, block +/-, track radio buttons w. • java.awt.event.ItemEvent – for Choice, List, Checkbox, and CheckboxMenuItem – stateChange indicates selected or deselected • java.awt.event.TextEventww – listeners are notified of every keystroke that changes the value – listeners are also notified when setText() is called • other subclasses are on the following pages Object Computing, Inc. 8 AWT Event Handling
  9. 9. om Event Object Contents .c (Cont’ d) DF • java.awt.AWTEvent – java.awt.event.ComponentEvent aP • id indicates moved, resized, shown, or hidden • java.awt.event.ContainerEvent – id indicates added or removed – child holds a reference to the component added or vi removed • java.awt.event.FocusEvent – id indicates gained or lost ee – temporary indicates temporary or permanent (see documentation in source) • java.awt.event.WindowEvent n – id indicates opened, closing, closed, iconified, deiconified, activated, and deactivated w. brought to frontww Object Computing, Inc. 9 AWT Event Handling
  10. 10. om Event Object Contents .c (Cont’ d) DF • java.awt.AWTEvent – java.awt.event.InputEvent aP • modifiers is a mask that holds – state of control, shift, and meta (alt) keys – state of mouse buttons 1, 2, & 3 • when holds time the event occurred vi – probably should have been put in java.util.EventObject! • java.awt.event.KeyEvent ee – id indicates typed, pressed, or released – keyChar holds the ascii code of the key pressed – keyCode holds a constant identifying the key pressed (needed for non-printable keys) n • java.awt.event.MouseEvent – id indicates clicked, pressed, released, moved, entered, w. exited, or dragged – clickCount holds # of times button was clicked – x,y hold location of mouse cursorww Object Computing, Inc. 10 AWT Event Handling
  11. 11. om Event Listener Interfaces .c • Class hierarchy and methods DF – java.util.EventListener • java.awt.event.ActionListener – actionPerformed • java.awt.event.AdjustmentListener aP – adjustmentValueChanged • java.awt.event.ComponentListener – componentHidden, componentMoved, componentResized, componentShown • java.awt.event.FocusListener vi – focusGained, focusLost • java.awt.event.ItemListener ee – itemStateChanged • java.awt.event.KeyListener – keyPressed, keyReleased, keyTyped • java.awt.event.MouseListener n – mouseEntered, mouseExited, mousePressed, mouseReleased, mouseClicked w. • java.awt.event.MouseMotionListener – mouseDragged, mouseMoved • java.awt.event.TextListener – textValueChangedww • java.awt.event.WindowListener – windowOpened, windowClosing, windowClosed, windowActivated, windowDeactivated, windowIconified, windowDeiconified Object Computing, Inc. 11 AWT Event Handling
  12. 12. om Event Sources and .c Their Listeners DF • Component (ALL components extend this) – ComponentListener, FocusListener, KeyListener, • Dialog - WindowListener aP MouseListener, MouseMotionListener • Frame - WindowListener vi • Button - ActionListener ee • Choice - ItemListener • Checkbox - ItemListener n • CheckboxMenuItem - ItemListener w. • List - ItemListener, ActionListener when an item is double-clicked • MenuItem - ActionListenerww • Scrollbar - AdjustmentListener • TextField - ActionListener, TextListener • TextArea - TextListener Object Computing, Inc. 12 AWT Event Handling
  13. 13. om Listener Adapter Classes .c DF • Provide empty default implementations of methods in listener interfaces with more than one method • They include aP vi – java.awt.event.ComponentAdapter – java.awt.event.FocusAdapter ee – java.awt.event.KeyAdapter – java.awt.event.MouseAdapter – java.awt.event.MouseMotionAdapter n – java.awt.event.WindowAdapter • To use, extend from them w. – override methods of interest – usefulness is limited by single inheritanceww • can’ do if another class is already being extended t • implementation for methods that are not of interest could look like this public void windowIconified(WindowEvent e) {} Object Computing, Inc. 13 AWT Event Handling
  14. 14. om Design For Flexibility .c and Maintainability DF invokes app. methods Event App Handlers • Can separate rs ne pa ates d nts liste cre sse GU co rs h re an – application code ss of iste App dlers t e as aP elf I mp an f., en rs n an on dle ve sse ha d – GUI code pa ates reg s cre GUI – event handling code • Steps to achieve this separation vi – create a single class whose constructor creates the entire GUI, possibly using other GUI-only classes ee – create the GUI by invoking this constructor from an application class – create classes whose only function is to be notified of n GUI events and invoke application methods • their constructors should accept references to application w. objects whose methods they will invoke – create event handling objects in a GUI class and register them with the components whose events theyww will handle Object Computing, Inc. 14 AWT Event Handling
  15. 15. om AWT Example .c DF aP vi • FontTest allows specification of text to be displayed, font name, style, color and size ee • It illustrates • creation of GUI components n • use of the Canvas and PopupMenu w. • component layout using BorderLayout, FlowLayout, and GridLayout • event handlingww • Invoke with <APPLET CODE=FontTest.class WIDTH=580 HEIGHT=250> </APPLET> Object Computing, Inc. 15 AWT Event Handling
  16. 16. om .c DF import java.awt.*; import java.awt.event.*; import java.util.Enumeration; import COM.ociweb.awt.ColorMap; aP public class FontTest extends java.applet.Applet implements ActionListener, AdjustmentListener, ItemListener, MouseListener { static final String DEFAULT_FONT = "Helvetica"; static final String DEFAULT_TEXT = "FontTest"; vi static final int DEFAULT_SIZE = 24; private static final int BOX_SIZE = 3; private static final int MIN_SIZE = 6; ee private static final int MAX_SIZE = 250; private CheckboxGroup styleGroup = new CheckboxGroup(); private Checkbox boldRadio = new Checkbox("Bold", false, styleGroup); private Checkbox bothRadio = new Checkbox("Both", false, styleGroup); n private Checkbox italicRadio = new Checkbox("Italic", false, styleGroup); w. private Checkbox plainRadio = new Checkbox("Plain", true, styleGroup); private Choice fontChoice = new Choice(); private List colorList = new List(4, false); private MyCanvas myCanvas = new MyCanvas(); private PopupMenu popup = new PopupMenu("Font");ww private Scrollbar scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, DEFAULT_SIZE, BOX_SIZE, MIN_SIZE, MAX_SIZE + BOX_SIZE); private TextField sizeField = new TextField(String.valueOf(DEFAULT_SIZE), 3); private TextField textField = new TextField(DEFAULT_TEXT, 40); Object Computing, Inc. 16 AWT Event Handling
  17. 17. om (Cont’d) .c DF public void init() { fontChoice.addItem("TimesRoman"); fontChoice.addItem("Helvetica"); fontChoice.addItem("Courier"); aP; Panel fontPanel = new Panel(); fontPanel.add(new Label("Font:")); fontPanel.add(fontChoice); vi Panel stylePanel = new Panel(); stylePanel.add(plainRadio); stylePanel.add(boldRadio); stylePanel.add(italicRadio); ee stylePanel.add(bothRadio); Enumeration e = ColorMap.getColorNames(); while (e.hasMoreElements()) { colorList.addItem((String) e.nextElement()); n }; w. Panel sizePanel = new Panel(); sizePanel.add (new Label("Size (" + MIN_SIZE + "-" + MAX_SIZE + ")")); sizePanel.add(sizeField);ww Panel westPanel = new Panel(new GridLayout(0, 1)); westPanel.add(fontPanel); unknown # of rows, westPanel.add(stylePanel); one column westPanel.add(colorList); westPanel.add(sizePanel); Object Computing, Inc. 17 AWT Event Handling
  18. 18. om (Cont’d) .c DF setLayout(new BorderLayout()); add(myCanvas, "Center"); add(westPanel, "West"); aP add(textField, "North"); add(scrollbar, "South"); fontChoice.addItemListener(this); plainRadio.addItemListener(this); boldRadio.addItemListener(this); vi italicRadio.addItemListener(this); bothRadio.addItemListener(this); colorList.addItemListener(this); sizeField.addActionListener(this); ee textField.addActionListener(this); scrollbar.addAdjustmentListener(this); fontPanel.addMouseListener(this); stylePanel.addMouseListener(this); sizePanel.addMouseListener(this); n myCanvas.addMouseListener(this); MenuItem timesRomanItem = new MenuItem("TimesRoman"); w. MenuItem helveticaItem = new MenuItem("Helvetica"); MenuItem courierItem = new MenuItem("Courier"); timesRomanItem.addActionListener(this); helveticaItem.addActionListener(this);ww courierItem.addActionListener(this); popup.add(timesRomanItem); popup.add(helveticaItem); popup.add(courierItem); add(popup); } Object Computing, Inc. 18 AWT Event Handling
  19. 19. om (Cont’d) .c public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == textField) { myCanvas.setText(textField.getText()); DF } else if (source == sizeField) { int size = Integer.parseInt(sizeField.getText()); scrollbar.setValue(size); setFont(); } else if (source instanceof MenuItem) { MenuItem menuItem = (MenuItem) source; } } setFont(); aP if (menuItem.getParent() == popup) {; } vi public void adjustmentValueChanged(AdjustmentEvent e) { if (e.getSource() == scrollbar) { ee sizeField.setText(String.valueOf(scrollbar.getValue())); setFont(); } } public void itemStateChanged(ItemEvent e) { n Object source = e.getSource(); if (source == fontChoice) { w. setFont(); } else if (source instanceof Checkbox) { Checkbox checkbox = (Checkbox) source; if (checkbox.getCheckboxGroup() == styleGroup) { setFont();ww } } else if (source == colorList) { Color color = ColorMap.getColor(colorList.getSelectedItem()); myCanvas.setColor(color); } } Object Computing, Inc. 19 AWT Event Handling
  20. 20. om (Cont’d) .c DF // MouseListener methods that need no action. public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} aP public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) { } e.getSource(), e.getX(), e.getY()); vi private void setFont() { int style = Font.PLAIN; Checkbox styleRadio = styleGroup.getSelectedCheckbox(); ee if (styleRadio == plainRadio) { style = Font.PLAIN; } else if (styleRadio == boldRadio) { style = Font.BOLD; } else if (styleRadio == italicRadio) { n style = Font.ITALIC; } else if (styleRadio == bothRadio) { w. style = Font.BOLD + Font.ITALIC; } Font font = new Font(fontChoice.getSelectedItem(),ww style, Integer.parseInt(sizeField.getText())); myCanvas.setFont(font); } } Object Computing, Inc. 20 AWT Event Handling
  21. 21. om (Cont’d) .c DF class MyCanvas extends Canvas { private Color color =; private Font font = new Font(FontTest.DEFAULT_FONT, Font.PLAIN, aP FontTest.DEFAULT_SIZE); private String text = FontTest.DEFAULT_TEXT; public void setColor(Color color) { vi this.color = color; repaint(); } ee public void setFont(Font font) { this.font = font; repaint(); } n public void setText(String text) { this.text = text; repaint(); w. } public void paint(Graphics g) { g.setColor(color); g.setFont(font);ww g.drawString(text, 10, 200); } } Object Computing, Inc. 21 AWT Event Handling
  22. 22. om .c DF package COM.ociweb.awt; import java.awt.Color; import java.util.Enumeration; import java.util.Hashtable; public class ColorMap { aP private static Hashtable hashtable = new Hashtable(); static { vi hashtable.put("White", Color.white); hashtable.put("Gray", Color.gray); hashtable.put("DarkGray", Color.darkGray); hashtable.put("Black",; ee hashtable.put("Red",; hashtable.put("Pink",; hashtable.put("Orange",; hashtable.put("Yellow", Color.yellow); hashtable.put("Green",; n hashtable.put("Magenta", Color.magenta); hashtable.put("Cyan", Color.cyan); hashtable.put("Blue",; w. } public static Color getColor(String name) { return (Color) hashtable.get(name);ww } public static Enumeration getColorNames() { return hashtable.keys(); } } Object Computing, Inc. 22 AWT Event Handling
  23. 23. om Appendix A .c DF JDK 1.0 AWT aP Event Handling vi n ee w.ww Object Computing, Inc. 23 AWT Event Handling
  24. 24. om 1.0 Default Event Handling .c (delegation-based event handling was added in Java 1.1) DF • Provided by Component class • handleEvent(Event evt) aP – first method invoked when an event occurs – default implementation tests for specific types of events and invokes the methods below vi • Methods to handle specific types of events – default implementations do nothing ee – they are • mouseDown and mouseUp • mouseDrag and mouseMove • mouseEnter and mouseExit n • keyDown and keyUp • gotFocus and lostFocus w. – from mouse click, tab key, or requestFocus method • action (discussed two slides ahead) • All event handling methods return booleanww – indicates whether they handled the event – if false, the event is handled recursively by containers Object Computing, Inc. 24 AWT Event Handling
  25. 25. om Overriding 1.0 Default Event Handling .c • Custom event handling methods other than DF handleEvent – created by overriding implementations in Component which do nothing aP – invoked by the default handleEvent implementation • Custom handleEvent method vi – created by overriding implementation in Component – can handle all events by comparing id field to constants in Event class to see what kind of event ee occurred – if overridden, other event handling methods will not be invoked unless n • they are invoked directly from this method – not recommended approach w. • this method invokes the handleEvent method of a superclass – recommended approach – do this if the event is not one you wish to handle in yourww handleEvent method – invoke with “return super.handleEvent(e); ” – first superclass to implement handleEvent is typically Component which disperses the event to methods which handle specific types of events Object Computing, Inc. 25 AWT Event Handling
  26. 26. om 1.0 Action Events .c • Most user interface components generate “action” events DF – Label and TextArea don’ generate any events t – List and Scrollbar generate events that are not “action” events • must be handled in a handleEvent method, aP not an action method • Default handleEvent invokes public boolean action(Event evt, Object what) vi • Second argument varies based on the component ee – Button • String representing button label – Checkbox (and radiobutton) n • Boolean state (true for on, false for off) • generated when picked w. – Choice (option menu) • String representing selected item – TextFieldww • null • generated when user presses return key • not when field is exited with mouse or tab key – use lostFocus method to catch that Object Computing, Inc. 26 AWT Event Handling
  27. 27. wwJava Tutorial Extending Classes and Interfaces Inheritance in Java w.Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the baseclass or superclass) with another class (called the derived class or subclass). In Java, neinheritance is used for two purposes:1. class inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the public methods and public data of the inheritance. ev base class. Java only allows a class to have one immediate base class, i.e., single class2. interface inheritance - create a new class to implement the methods defined as part of an ia interface for the purpose of subtyping. That is a class that implements an interface “conforms to” (or is constrained by the type of) the interface. Java supports multiple interface inheritance. PDIn Java, these two kinds of inheritance are made distinct by using different language syntax. Forclass inheritance, Java uses the keyword extends and for interface inheritance Java uses thekeyword implements.public class derived-class-name extends base-class-name { // derived class methods extend and possibly override F. co // those of the base class}public class class-name implements interface-name {} // class provides an implementation for the methods // as specified by the interface mGreg Lavender Slide 1 of 12 6/15/99
  28. 28. wwJava Tutorial Extending Classes and Interfaces Example of class inhertiance w.package MyPackage; neclass Base { private int x; public int f() { ... } ev protected int g() { ... }}class Derived extends Base { private int y; ia public int f() { /* new implementation for Base.f() */ } PD public void h() { y = g(); ... }}In Java, the protected access qualifier means that the protected item (field or method) is visible to a F.any derived class of the base class containing the protected item. It also means that the protecteditem is visible to methods of other classes in the same package. This is different from C++. coQ: What is the base class of class Object? I.e., what would you expect to get if you executed thefollowing code?Object x = new Object();System.out.println(x.getClass().getSuperclass()); mGreg Lavender Slide 2 of 12 6/15/99
  29. 29. wwJava Tutorial Extending Classes and Interfaces Order of Construction under Inheritance w.Note that when you construct an object, the default base class constructor is called implicitly, beforethe body of the derived class constructor is executed. So, objects are constructed top-down under neinheritance. Since every object inherits from the Object class, the Object() constructor is alwayscalled implicitly. However, you can call a superclass constructor explicitly using the builtin superkeyword, as long as it is the first statement in a constructor. evFor example, most Java exception objects inherit from the java.lang.Exception class. If you wroteyour own exception class, say SomeException, you might write it as follows: iapublic class SomeException extends Exception { public SomeException() { } public SomeException(String s) { PD super(); // calls Exception(), which ultimately calls Object() } F. super(s); // calls Exception(String), to pass argument to base class public SomeException (int error_code) { this("error”); // class constructor above, which calls super(s) System.err.println(error_code); co} } mGreg Lavender Slide 3 of 12 6/15/99
  30. 30. wwJava Tutorial Extending Classes and Interfaces Abstract Base Classes w.An abstract class is a class that leaves one or more method implementations unspecified bydeclaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A nesubclass is required to override the abstract method and provide an implementation. Hence, anabstract class is incomplete and cannot be instantiated, but can be used as a base class.abstract public class abstract-base-class-name { ev // abstract class has at least one abstract method public abstract return-type abstract-method-name ( formal-params ); ia ... // other abstract methods, object methods, class methods PD}public class derived-class-name extends abstract-base-class-name { public return-type abstract-method-name (formal-params) { stmt-list; } ... // other method implementations F. co}It would be an error to try to instantiate an object of an abstract type:abstract-class-name obj = new abstract-class-name();That is, operator new is invalid when applied to an abstract class. // ERROR! mGreg Lavender Slide 4 of 12 6/15/99
  31. 31. wwJava Tutorial Extending Classes and Interfaces Example abstract class usage w.abstract class Point { private int x, y; ne public Point(int x, int y) { this.x = x; this.y = y; } public void move(int dx, int dy) { x += dx; y += dy; plot(); } ev public abstract void plot(); // has no implementation}abstract class ColoredPoint extends Point { private int color; ia protected public ColoredPoint(int x, int y, int color) PD { super(x, y); this.color = color; }}class SimpleColoredPoint extends ColoredPoint { F. public SimpleColoredPoint(int x, int y, int color) { super(x,y,color); } public void plot() { ... } // code to plot a SimpleColoredPoint} coSince ColoredPoint does not provide an implementation of the plot method, it must be declaredabstract. The SimpleColoredPoint class does implement the inherited plot method. It would be anerror to try to instantiate a Point object or a ColoredPoint object. However, you can declare a Point mreference and initialize it with an instance of a subclass object that implements the plot method:Point p = new SimpleColoredPoint(a, b, red); p.plot();Greg Lavender Slide 5 of 12 6/15/99
  32. 32. wwJava Tutorial Extending Classes and Interfaces Interfaces w.An abstract class mixes the idea of mutable data in the form of instance variables, non-abstractmethods, and abstract methods. An abstract class with only static final instance variables and all neabstract methods is called an interface. An interface is a specification, or contract, for a set ofmethods that a class that implements the interface must conform to in terms of the type signature ofthe methods. The class that implements the interface provides an implementation for each method,just as with an abstract method in an abstract class. evSo, you can think of an interface as an abstract class with all abstract methods. The interface itselfcan have either public, package, private or protected access defined. All methods declared in an iainterface are implicitly abstract and implicitly public. It is not necessary, and in fact consideredredundant to declare a method in an interface to be interface, then they are implicitly defined to be:• public. PDYou can define data in an interface, but it is less common to do so. If there are data fields defined in• static, and• final F.In other words, any data defined in an interface are treated as public constants. co mNote that a class and an interface in the same package cannot share the same name.Methods declared in an interace cannot be declared final. Why?Greg Lavender Slide 6 of 12 6/15/99
  33. 33. wwJava Tutorial Extending Classes and Interfaces Interface declaration w.Interface names and class names in the same package must be distinct. nepublic interface interface-name { // if any data are defined, they must be constants public static final type-name var-name = constant-expr; ev // one or more implicitly abstract and public methods return-type method-name ( formal-params ); ia}An interface declaraion is nothing more than a specification to which some class that purports to PDimplement the interface must conform to in its implementation. That is, a class the implements theinterface must have defined implementations for each of the interface methods.The major reason for interfaces being distinct elements in Java is that you often want to define some F.operation to operate on objects that all conform to the same interface. So, you can define some code ina very general way, with a guarantee that by only using the methods defined in the interface, that all coobjects that implement the interface will have defined implementations for all the methods.For example, you might define a Shape interface that defines an area() method, and so you wouldexpect that any class that implements the Shape interface, would define an area method. So, if I mhave a list of references to objects that implement the Shape interface, I can legitimately invoke thearea method, abstractly, on each of these objects and expect to obtain as a result a value thatrepresents the area of some shape.Greg Lavender Slide 7 of 12 6/15/99
  34. 34. wwJava Tutorial Extending Classes and Interfaces Separation of Interface from Implementations w.Interfaces are specifications for many possible implementations. Interfaces are used to define acontract for how you interact with an object, independent of the underlying implementation. The neobjective of an object-oriented programmer is to separate the specification of the interface from thehidden details of the implementation.Consider the specification of a common LIFO stack.public interface StackInterface { boolean empty(); ev ia void push(Object x); Object pop() throws EmptyStackException; Object peek() throws EmptyStackException;} PDNote that the methods in this interface are defined to operate on objects of type Object. Since a stackis a “container type”, it is very common to use the base class for all objects, namely Object, as the F.type of the arguments and results to a container type. Since all objects ultimately inherit from classObject, we can always generically refer to any object in the system using an Object reference. coHowever, when we pop from a stack, we have to explicitly type case from the very general typeObject to a concrete type, so that we can manipulate the object concretely.Q: How many different ways are there to implement a stack? If we are using just using a Stack object m(as opposed to implementing it ourselves) should we care?Greg Lavender Slide 8 of 12 6/15/99
  35. 35. wwJava Tutorial Extending Classes and Interfaces Stack implementation of the StackInterface w.public class Stack implements StackInterface { ne private Vector v = new Vector(); // use java.util.Vector class ev public boolean empty() { return v.size() == 0; } public void push(Object item) { v.addElement(item); } public Object pop() { Object obj = peek(); ia PD v.removeElementAt(v.size() - 1); return obj; } F. public Object peek() throws EmptyStackException { if (v.size() == 0) throw new EmptyStackException(); co return v.elementAt(v.size() - 1); }} mGreg Lavender Slide 9 of 12 6/15/99
  36. 36. wwJava Tutorial Extending Classes and Interfaces Should a stack use or inherit from a vector? w.The java.util.Stack class is defined as a subclass of the java.util.Vector class, rather than using aVector object as in the previous example. This sort of inheritance is not subtype inheritance, because nethe interface of a Stack object can be violated because a Vector has a “wider” interface than a Stack,i.e., a vector allows insertion into the front and the rear, so it is possible to violate the stack contractby treating a stack object as a vector, and violating the LIFO specification of a stack.public class Stack extends Vector { ev public Object push(Object item) {addElement(item); return item;} public Object pop() { ia Object obj; int len = size(); PD obj = peek(); removeElementAt(len - 1); return obj; } public Object peek() { int len = size(); if (len == 0) throw new EmptyStackException(); F. co return elementAt(len - 1); } public boolean empty() { return size() == 0;}}Vector v = new Stack(); // legal - base class reference to subclass objectv.insertElementAt(x, 2); // insert object x into Vector slot 2!! mGreg Lavender Slide 10 of 12 6/15/99
  37. 37. wwJava Tutorial Extending Classes and Interfaces When to use an Interface vs when to use an abstract class w.Having reviewed their basic properties, there are two primary differences between interfaces andabstract classes: ne• an abstract class can have a mix of abstract and non-abstract methods, so some default implementations can be defined in the abstract base class. An abstract class can also have static methods, static data, private and protected methods, etc. In other words, a class is a class, so it ev can contain features inherent to a class. The downside to an abstract base class, is that since their is only single inheritance in Java, you can only inherit from one class.• an interface has a very restricted use, namely, to declare a set of public abstract method ia singatures that a subclass is required to implement. An interfaces defines a set of type constraints, in the form of type signatures, that impose a requirement on a subclass to implement the methods of the interface. Since you can inherit multiple interfaces, they are often a very PD useful mechanism to allow a class to have different behaviors in different situations of usage by implementing multiple interfaces. F.It is usually a good idea to implement an interface when you need to define methods that are to beexplicitly overridden by some subclass. If you then want some of the methods implemented with codefault implementations that will be inherited by a subclass, then create an implementation classfor the interface, and have other class inherit (extend) that class, or just use an abstract base classinstead of an interface. mGreg Lavender Slide 11 of 12 6/15/99
  38. 38. wwJava Tutorial Extending Classes and Interfaces Example of default interface implementations java-06.fminterface X { void f(); w. ne int g();} evclass XImpl implements X { void g() { return -1; } // default implementation for g()}class Y extends XImpl implements X { void f() { ... } // provide implementation for f() ia PD}Note that when you invoke an abtract method using a reference of the type of an abstract class or aninterface, the method call is dynamically dispatched.X x = new Y();x.f(); F. coThe call x.f() causes a run-time determination of the actual type of object that ‘x’ refers to, then amethod lookup to determine which implementation of f() to invoke. In this case, Y.f(x) is called, butthe type of x is first converted to Y so that the ‘this’ reference is initialized to a reference of type Yinside of f(), since the implicit type signature of Y.f() is really Y.f(final Y this); mGreg Lavender Slide 12 of 12 6/15/99
  39. 39. ww w.n ee vi aP DF Java Array1
  40. 40. DF Agenda aP ● What is an array vi ● Declaration of an array ee ● Instantiation of an array ● Accessing array element .n ● Array length ● Multi-dimensional array www 2
  41. 41. DF aP vi ee .n w What is an Array?ww 3
  42. 42. DF Introduction to Arrays aP ● Suppose we have here three variables of type int with vi different identifiers for each variable. ee int number1; int number2; int number3; .n number1 = 1; number2 = 2; w number3 = 3;ww As you can see, it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose. 4
  43. 43. DF Introduction to Arrays aP ● In Java and other programming languages, there is one vi capability wherein we can use one variable to store a list of data and manipulate them more efficiently. This type of ee variable is called an array. .n ● An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots. www 5
  44. 44. DF aP vi ee .n Declaration of www an Array 6
  45. 45. DF Declaring Arrays aP ● To declare an array, write the data type, followed by a set of vi square brackets[], followed by the identifier name. ee ● For example, int []ages; .n or int ages[]; www 7
  46. 46. DF aP vi ee .n Instantiation of www an Array 8
  47. 47. DF Array Instantiation aP ● After declaring, we must create the array and specify its vi length with a constructor statement. ee ● Definitions: – Instantiation .n ● In Java, this means creation w – Constructor ● In order to instantiate an object, we need to use a constructor for this. Aww constructor is a method that is called to create a certain object. ● We will cover more about instantiating objects and constructors later. 9
  48. 48. DF Array Instantiation aP ● To instantiate (or create) an array, write the new keyword, vi followed by the square brackets containing the number of elements you want the array to have. ee ● For example, //declaration .n int ages[]; //instantiate object w ages = new int[100]; or, can also be written as,ww //declare and instantiate object int ages[] = new int[100]; 10
  49. 49. DF Array Instantiation aP vi ee .n www 11
  50. 50. DF Array Instantiation aP ● You can also instantiate an array by directly initializing it with vi data. ee ● For example, int arr[] = {1, 2, 3, 4, 5}; .n This statement declares and instantiates an array of integers with five elements (initialized to the values 1, 2, 3, 4, and 5). www 12
  51. 51. DF Sample Program aP 1 //creates an array of boolean variables with identifier 2 //results. This array contains 4 elements that are vi 3 //initialized to values {true, false, true, false} 4 5 boolean results[] = { true, false, true, false }; ee 6 7 //creates an array of 4 double variables initialized 8 //to the values {100, 90, 80, 75}; 9 .n 10 double []grades = {100, 90, 80, 75}; 11 12 //creates an array of Strings with identifier days and w 13 //initialized. This array contains 7 elements 14 15 String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”,ww “Sun”}; 13
  52. 52. DF aP vi ee .n w Accessing Arrayww Element 14
  53. 53. DF Accessing an Array Element aP ● To access an array element, or a part of the array, you use vi a number called an index or a subscript. ee ● index number or subscript – assigned to each member of the array, to allow the program to .n access an individual member of the array. – begins with zero and progress sequentially by whole numbers to the w end of the array. – NOTE: Elements inside your array are from 0 to (sizeOfArray-1).ww 15
  54. 54. DF Accessing an Array Element aP ● For example, given the array we declared a while ago, we vi have //assigns 10 to the first element in the array ee ages[0] = 10; //prints the last element in the array .n System.out.print(ages[99]); www 16
  55. 55. DF Accessing an Array Element aP ● NOTE: vi – once an array is declared and constructed, the stored value of each member of the array will be initialized to zero for number data. ee – for reference data types such as Strings, they are NOT initialized to blanks or an empty string “”. Therefore, you must populate the String arrays explicitly. w .nww 17
  56. 56. DF Accessing an Array Element aP ● The following is a sample code on how to print all the vi elements in the array. This uses a for loop, so our code is shorter. ee 1 public class ArraySample{ 2 public static void main( String[] args ){ .n 3 int[] ages = new int[100]; 4 for( int i=0; i<100; i++ ){ 5 System.out.print( ages[i] ); w 6 } 7 } 8 }ww 18
  57. 57. DF Coding Guidelines aP 1. It is usually better to initialize or instantiate the vi array right away after you declare it. For example, the declaration, ee int []arr = new int[100]; .n is preferred over, w int []arr;ww arr = new int[100]; 19
  58. 58. DF Coding Guidelines aP 2. The elements of an n-element array have indexes vi from 0 to n-1. Note that there is no array element arr[n]! This will result in an array-index-out-of- ee bounds exception. .n 3. Remember: You cannot resize an array. www 20
  59. 59. DF aP vi ee .n w Array Lengthww 21
  60. 60. DF Array Length aP ● In order to get the number of elements in an array, you can vi use the length field of an array. ee ● The length field of an array returns the size of the array. It can be used by writing, .n arrayName.length www 22
  61. 61. DF Array Length aP1 public class ArraySample {2 public static void main( String[] args ){ vi3 int[] ages = new int[100];4 ee5 for( int i=0; i<ages.length; i++ ){6 System.out.print( ages[i] );7 }8 } .n9 } www 23
  62. 62. DF Coding Guidelines aP 1. When creating for loops to process the elements of an vi array, use the array objects length field in the condition statement of the for loop. This will allow the loop to adjust ee automatically for different-sized arrays. .n 2. Declare the sizes of arrays in a Java program using named constants to make them easy to change. For example, w final int ARRAY_SIZE = 1000; //declare a constantww . . . int[] ages = new int[ARRAY_SIZE]; 24
  63. 63. DF aP vi ee .n Multi-Dimensional www Array 25
  64. 64. DF Multidimensional Arrays aP ● Multidimensional arrays are implemented as arrays of vi arrays. ee ● Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name. w .nww 26
  65. 65. DF Multidimensional Arrays aP ● For example, vi // integer array 512 x 128 elements ee int[][] twoD = new int[512][128]; // character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24]; .n // String array 4 rows x 2 columns w String[][] dogs = {{ "terry", "brown" }, { "Kristin", "white" }, { "toby", "gray"},ww { "fido", "black"} }; 27
  66. 66. DF Multidimensional Arrays aP ● To access an element in a multidimensional array is just the vi same as accessing the elements in a one dimensional array. ee ● For example, to access the first element in the first row of the array dogs, we write, .n System.out.print( dogs[0][0] ); w This will print the String "terry" on the screen.ww 28
  67. 67. DF Summary aP ● Arrays vi – Definition ee – Declaration – Instantiation and constructors (brief overview – to be discussed more later) .n – Accessing an element – The length field w – Multidimensional Arraysww 29
  68. 68. ww core w. ne evprogramming Handling iMouse and aP DF Keyboard Events .c om1 © 2001-2003 Marty Hall, Larry Brown
  69. 69. ww Agenda w. • • ne General event-handling strategy Handling events with separate listeners • ev Handling events by implementing interfaces • Handling events with named inner classes ia • Handling events with anonymous inner classes PD • The standard AWT listener types • Subtleties with mouse events F. • Examples co m2 Handling Mouse and Keyboard Events
  70. 70. ww General Strategy w. ne • Determine what type of listener is of interest – 11 standard AWT listener types, described on later slide. ev • ActionListener, AdjustmentListener, ComponentListener, ContainerListener, ia FocusListener, ItemListener, KeyListener, WindowListener • Define a class of that type PD MouseListener, MouseMotionListener, TextListener, F. – Implement interface (KeyListener, MouseListener, etc.) – Extend class (KeyAdapter, MouseAdapter, etc.) • Register an object of your listener class co with the window – w.addXxxListener(new MyListenerClass()); • E.g., addKeyListener, addMouseListener m3 Handling Mouse and Keyboard Events
  71. 71. ww Events with a Handling w. Separate Listener: Simple Case ne • Listener does not need to call any methods of the window to which it is attached ev import java.applet.Applet; ia import java.awt.*; PD public class ClickReporter extends Applet { public void init() { F. setBackground(Color.yellow); addMouseListener(new ClickListener()); } } co m4 Handling Mouse and Keyboard Events
  72. 72. ww Listener: Simple Case Separate w. (Continued) ne import java.awt.event.*; ev public class ClickListener extends MouseAdapter { public void mousePressed(MouseEvent event) { ia System.out.println("Mouse pressed at (" + event.getX() + "," + } PD event.getY() + ")."); } F. co m5 Handling Mouse and Keyboard Events
  73. 73. ww Generalizing Simple Case w. ne • What if ClickListener wants to draw a circle wherever mouse is clicked? ev • Why can’t it just call getGraphics to get a Graphics object with which to draw? ia • General solution: PD – Call event.getSource to obtain a reference to window or GUI component from which event originated – Cast result to type of interest F. – Call methods on that reference co m6 Handling Mouse and Keyboard Events
  74. 74. ww Events with Separate Handling w. Listener: General Case ne import java.applet.Applet; ev import java.awt.*; ia public class CircleDrawer1 extends Applet { public void init() { PD setForeground(; addMouseListener(new CircleListener()); } } F. co m7 Handling Mouse and Keyboard Events
  75. 75. ww Listener: General Separate w. Case (Continued) ne import java.applet.Applet; import java.awt.*; ev import java.awt.event.*; ia public class CircleListener extends MouseAdapter { private int radius = 25; PD public void mousePressed(MouseEvent event) { Applet app = (Applet)event.getSource(); F. Graphics g = app.getGraphics(); g.fillOval(event.getX()-radius, co event.getY()-radius, 2*radius, } } 2*radius); m8 Handling Mouse and Keyboard Events
  76. 76. ww Listener: General Separate w. Case (Results) ne ev ia PD F. co m9 Handling Mouse and Keyboard Events
  77. 77. ww 2: Implementing a Case w. Listener Interface ne import java.applet.Applet; import java.awt.*; ev import java.awt.event.*; ia public class CircleDrawer2 extends Applet implements MouseListener { PD private int radius = 25; public void init() { F setForeground(; addMouseListener(this); .c } om10 Handling Mouse and Keyboard Events
  78. 78. ww Implementing a Listener w. Interface (Continued) ne public public void void mouseEntered(MouseEvent event) {} mouseExited(MouseEvent event) {} public public ev void void mouseReleased(MouseEvent event) {} mouseClicked(MouseEvent event) {} ia PD public void mousePressed(MouseEvent event) { Graphics g = getGraphics(); g.fillOval(event.getX()-radius, F event.getY()-radius, 2*radius, 2*radius); .c } } om11 Handling Mouse and Keyboard Events
  79. 79. ww Case 3: Named Inner Classes w. import java.applet.Applet; import java.awt.*; ne import java.awt.event.*; ev ia public class CircleDrawer3 extends Applet { public void init() { setForeground(; addMouseListener(new CircleListener());PD } F. co m12 Handling Mouse and Keyboard Events
  80. 80. ww Inner Classes Named w. (Continued) ne • Note: still part of class from previous slide ev private class CircleListener extends MouseAdapter { ia private int radius = 25; PD public void mousePressed(MouseEvent event) { Graphics g = getGraphics(); F g.fillOval(event.getX()-radius, event.getY()-radius, 2*radius, .c } } 2*radius); om }13 Handling Mouse and Keyboard Events
  81. 81. ww 4: Anonymous Inner Case w. Classes ne public class CircleDrawer4 extends Applet { public void init() { ev setForeground(; addMouseListener (new MouseAdapter() { ia private int radius = 25; PD public void mousePressed(MouseEvent event) { Graphics g = getGraphics(); F. g.fillOval(event.getX()-radius, event.getY()-radius, } co 2*radius, 2*radius); } } }); m14 Handling Mouse and Keyboard Events
  82. 82. ww Handling Strategies: Event w. Pros and Cons ne • Separate Listener – Advantages ev • Can extend adapter and thus ignore unused methods • Separate class easier to manage ia – Disadvantage PD • Need extra step to call methods in main window • Main window that implements interface – Advantage F. • No extra steps needed to call methods in main window – Disadvantage co • Must implement methods you might not care about m15 Handling Mouse and Keyboard Events
  83. 83. ww Handling Strategies: Event w. Pros and Cons (Continued) ne • Named inner class – Advantages ev • Can extend adapter and thus ignore unused methods • No extra steps needed to call methods in main ia window – Disadvantage PD • A bit harder to understand • Anonymous inner class – Advantages F. co • Same as named inner classes • Even shorter – Disadvantage m • Much harder to understand16 Handling Mouse and Keyboard Events
  84. 84. ww AWT Event Listeners Standard w. (Summary) ne Adapter Class ev Listener ActionListener (If Any) Registration Method addActionListener ia AdjustmentListener ComponentListener ComponentAdapter addAdjustmentListener addComponentListener FocusListener ItemListener PD ContainerListener ContainerAdapter FocusAdapter addContainerListener addFocusListener addItemListener KeyListener MouseListener F. KeyAdapter MouseAdapter addKeyListener addM ouseListener MouseMotionListener TextListener WindowListener co MouseMotionAdapter WindowAdapter addM ouseMotionListener addTextListener addWindowListener m17 Handling Mouse and Keyboard Events
  85. 85. ww AWT Event Listeners Standard w. (Details) ne • ActionListener – Handles buttons and a few other actions ev • actionPerformed(ActionEvent event) • AdjustmentListener ia – Applies to scrolling PD • adjustmentValueChanged(AdjustmentEvent event) • ComponentListener • F. – Handles moving/resizing/hiding GUI objects componentResized(ComponentEvent event) • • co componentMoved (ComponentEvent event) componentShown(ComponentEvent event) • m componentHidden(ComponentEvent event)18 Handling Mouse and Keyboard Events
  86. 86. ww AWT Event Listeners Standard w. (Details Continued) ne • ContainerListener – Triggered when window adds/removes GUI controls ev • componentAdded(ContainerEvent event) • componentRemoved(ContainerEvent event) • FocusListeneria PD – Detects when controls get/lose keyboard focus • focusGained(FocusEvent event) F. • focusLost(FocusEvent event) co m19 Handling Mouse and Keyboard Events
  87. 87. ww AWT Event Listeners Standard w. (Details Continued) ne • ItemListener – Handles selections in lists, checkboxes, etc. ev • itemStateChanged(ItemEvent event) • KeyListener ia – Detects keyboard events PD • keyPressed(KeyEvent event) -- any key pressed down F. • keyReleased(KeyEvent event) -- any key released • keyTyped(KeyEvent event) -- key for printable char released co m20 Handling Mouse and Keyboard Events
  88. 88. ww AWT Event Listeners Standard w. (Details Continued) ne • MouseListener – Applies to basic mouse events • •ev mouseEntered(MouseEvent event) mouseExited(MouseEvent event) • ia mousePressed(MouseEvent event) • • PD mouseReleased(MouseEvent event) mouseClicked(MouseEvent event) -- Release without drag F. – Applies on release if no movement since press • MouseMotionListener co – Handles mouse movement m • mouseMoved(MouseEvent event) • mouseDragged(MouseEvent event)21 Handling Mouse and Keyboard Events
  89. 89. ww AWT Event Listeners Standard w. (Details Continued) ne • TextListener – Applies to textfields and text areas ev • textValueChanged(TextEvent event) • WindowListener ia – Handles high-level window events PD • windowOpened, windowClosing, windowClosed, windowIconified, windowDeiconified, F. windowActivated, windowDeactivated – windowClosing particularly useful co m22 Handling Mouse and Keyboard Events
  90. 90. ww Mouse Events: Details w. ne • MouseListener and MouseMotionListener share event types • Location of clicks ev – event.getX() and event.getY() • Double clicks ia – Determined by OS, not by programmer – Call event.getClickCount() PD • Distinguishing mouse buttons F. – Call event.getModifiers() and compare to MouseEvent.Button2_MASK for a middle click and co MouseEvent.Button3_MASK for right click. – Can also trap Shift-click, Alt-click, etc. m23 Handling Mouse and Keyboard Events
  91. 91. ww Example: Spelling- Simple w. Correcting Textfield ne • KeyListener corrects spelling during typing • ActionListener completes word on ENTER ev • FocusListener gives subliminal hints ia PD F. co m24 Handling Mouse and Keyboard Events
  92. 92. ww Example: Simple Whiteboard w. import java.applet.Applet; import java.awt.*; ne import java.awt.event.*; ev public class SimpleWhiteboard extends Applet { protected int lastX=0, lastY=0; ia public void init() { setBackground(Color.white); PD setForeground(; addMouseListener(new PositionRecorder()); F. } addMouseMotionListener(new LineDrawer()); co protected void record(int x, int y) { } lastX = x; lastY = y; m25 Handling Mouse and Keyboard Events
  93. 93. ww Simple Whiteboard (Continued) w. ne private class PositionRecorder extends MouseAdapter { ev public void mouseEntered(MouseEvent event) { requestFocus(); // Plan ahead for typing } record(event.getX(), event.getY()); ia PD public void mousePressed(MouseEvent event) { record(event.getX(), event.getY()); } } F. ... co m26 Handling Mouse and Keyboard Events
  94. 94. ww Simple Whiteboard (Continued) w. ... ne ev private class LineDrawer extends MouseMotionAdapter { public void mouseDragged(MouseEvent event) { int x = event.getX(); int y = event.getY(); ia Graphics g = getGraphics(); g.drawLine(lastX, lastY, x, y); record(x, y); PD } } F. } co m27 Handling Mouse and Keyboard Events
  95. 95. ww Simple Whiteboard (Results) w. ne ev ia PD F. co m28 Handling Mouse and Keyboard Events
  96. 96. ww Whiteboard: Adding Keyboard w. Events ne import java.applet.Applet; import java.awt.*; ev import java.awt.event.*; public class Whiteboard extends SimpleWhiteboard { ia protected FontMetrics fm; PD public void init() { super.init(); F. Font font = new Font("Serif", Font.BOLD, 20); setFont(font); } co fm = getFontMetrics(font); addKeyListener(new CharDrawer()); m29 Handling Mouse and Keyboard Events