Inheritance (cont) Abstract Classes

Similar documents
Interfaces. consider an interface for mathematical functions of the form

Inheritance (Part 5) Odds and ends

Inheritance, cont. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance (Part 2) Notes Chapter 6

Based on slides by Prof. Burton Ma

Implementing Graphical User Interfaces

Building Graphical User Interfaces. Overview

Building Graphical User Interfaces. GUI Principles

Queens College, CUNY Department of Computer Science. CS 212 Object-Oriented Programming in Java Practice Exam 2. CS 212 Exam 2 Study Guide

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Graphical User Interface (GUI)

INHERITANCE. Spring 2019

Window Interfaces Using Swing Objects

Java Magistère BFA

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Java Object Oriented Design. CSC207 Fall 2014

A Simple Text Editor Application

8. Polymorphism and Inheritance

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

More about inheritance

Window Interfaces Using Swing Objects

Chapter 6 Introduction to Defining Classes

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Graphical User Interface (GUI)

Java Fundamentals (II)

Rules and syntax for inheritance. The boring stuff

Polymorphism. return a.doublevalue() + b.doublevalue();

MIT AITI Swing Event Model Lecture 17

Java Classes, Inheritance, and Interfaces

CS-202 Introduction to Object Oriented Programming

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

CS Exam 1 Review Suggestions

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

The class Object. Lecture CS1122 Summer 2008

Graphical User Interfaces. Comp 152

We are on the GUI fast track path

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

GUI Event Handlers (Part I)

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

Inheritance and Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object-Oriented Concepts

CS11 Java. Fall Lecture 3

2. (True/False) All methods in an interface must be declared public.

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

CS 251 Intermediate Programming Inheritance

Introduction to Inheritance

AP CS Unit 6: Inheritance Notes

Object-Oriented Programming: Revision. Revision / Graphics / Subversion. Ewan Klein. Inf1 :: 2008/09

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Chapter 5. Inheritance

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

Inheritance. Chapter 7. Chapter 7 1

Midterm assessment - MAKEUP Fall 2010

First IS-A Relationship: Inheritance

Chapter 13 Lab Advanced GUI Applications

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

PIC 20A GUI with swing

Review sheet for Final Exam (List of objectives for this course)

CS 11 java track: lecture 3

Java Application Development

Introduction to the JAVA UI classes Advanced HCI IAT351

Class, Variable, Constructor, Object, Method Questions

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

Widgets. Widgets Widget Toolkits. User Interface Widget

Inheritance (continued) Inheritance

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

import javax.swing.*; import java.awt.*; import java.awt.event.*;

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Java Programming Lecture 6

COMP 250: Java Object Oriented Programming

CLASS DESIGN. Objectives MODULE 4

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Inheritance. Transitivity

CS 180 Final Exam Review 12/(11, 12)/08

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

More Swing. CS180 Recitation 12/(04,05)/08

C12a: The Object Superclass and Selected Methods

Widgets. Widgets Widget Toolkits. 2.3 Widgets 1

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Intro to Computer Science 2. Inheritance

Practical Scala. Dianne Marsh Emerging Technology for the Enterprise Conference 03/26/2009

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

Inheritance, Polymorphism, and Interfaces

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

Methods Common to all Classes

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Transcription:

Inheritance (cont) Abstract Classes 1

Polymorphism inheritance allows you to define a base class that has fields and methods classes derived from the base class can use the public and protected base class fields and methods polymorphism allows the implementer to change the behaviour of the derived class methods 2

// client code public void print(dog d) { System.out.println( d.tostring() ); Dog tostring CockerSpaniel tostring Mix tostring // later on... Dog fido = new Dog(); CockerSpaniel lady = new CockerSpaniel(); Mix mutt = new Mix(); this.print(fido); this.print(lady); this.print(mutt); 3

notice that fido, lady, and mutt were declared as Dog, CockerSpaniel, and Mutt what if we change the declared type of fido, lady, and mutt? 4

// client code public void print(dog d) { System.out.println( d.tostring() ); Dog tostring CockerSpaniel tostring Mix tostring // later on... Dog fido = new Dog(); Dog lady = new CockerSpaniel(); Dog mutt = new Mix(); this.print(fido); this.print(lady); this.print(mutt); 5

what if we change the print method parameter type to Object? 6

// client code public void print(object obj) { System.out.println( obj.tostring() ); // later on... Dog fido = new Dog(); Dog lady = new CockerSpaniel(); Dog mutt = new Mix(); this.print(fido); this.print(lady); this.print(mutt); this.print(new Date()); Dog tostring CockerSpaniel tostring Mix tostring Date tostring 7

Late Binding polymorphism requires late binding of the method name to the method definition late binding means that the method definition is determined at run-time non-static method obj.tostring() run-time type of the instance obj 8

Declared vs Run-time type Dog lady = new CockerSpaniel(); declared type run-time or actual type 9

the declared type of an instance determines what methods can be used Dog lady = new CockerSpaniel(); the name lady can only be used to call methods in Dog lady.somecockerspanielmethod() won't compile 10

Dynamic dispatch the actual type of the instance determines what definition is used when the method is called Dog lady = new CockerSpaniel(); lady.tostring() uses the CockerSpaniel definition of tostring selecting which version of a polymorphic method to use at run-time is called dynamic dispatch 11

12 Abstract classes

Abstract Classes sometimes you will find that you want the API for a base class to have a method that the base class cannot define e.g. you might want to know what a Dog's bark sounds like but the sound of the bark depends on the breed of the dog you want to add the method bark to Dog but only the subclasses of Dog can implement bark 13

Abstract Classes sometimes you will find that you want the API for a base class to have a method that the base class cannot define e.g. you might want to know the breed of a Dog but only the subclasses have information about the breed you want to add the method getbreed to Dog but only the subclasses of Dog can implement getbreed 14

if the base class has methods that only subclasses can define and the base class has fields common to all subclasses then the base class should be abstract if you have a base class that just has methods that it cannot implement then you probably want an interface abstract : (dictionary definition) existing only in the mind in Java an abstract class is a class that you cannot make instances of e.g. http://docs.oracle.com/javase/7/docs/api/java/util/abstractlist.html 15

an abstract class provides a partial definition of a class the "partial definition" contains everything that is common to all of the subclasses the subclasses complete the definition an abstract class can define fields and methods subclasses inherit these an abstract class can define constructors subclasses must call these an abstract class can declare abstract methods 16 subclasses must define these (unless the subclass is also abstract)

Abstract Methods an abstract base class can declare, but not define, zero or more abstract methods public abstract class Dog { // fields, ctors, regular methods public abstract String getbreed(); the base class is saying "all Dogs can provide a String describing the breed, but only the subclasses know enough to implement the method" 17

Abstract Methods the non-abstract subclasses must provide definitions for all abstract methods consider getbreed in Mix 18

public class Mix extends Dog { // stuff from before... @Override public String getbreed() { if(this.breeds.isempty()) { return "mix of unknown breeds"; StringBuffer b = new StringBuffer(); b.append("mix of"); for(string breed : this.breeds) { b.append(" " + breed); return b.tostring(); 19

PureBreed a purebreed dog is a dog with a single breed one String field to store the breed note that the breed is determined by the subclasses the class PureBreed cannot give the breed field a value but it can implement the method getbreed the class PureBreed defines an field common to all subclasses and it needs the subclass to inform it of the actual breed PureBreed is also an abstract class 20

public abstract class PureBreed extends Dog { private String breed; public PureBreed(String breed) { super(); this.breed = breed; public PureBreed(String breed, int size, int energy) { super(size, energy); this.breed = breed; 21

@Override public String getbreed() { return this.breed; 22

Subclasses of PureBreed the subclasses of PureBreed are responsible for setting the breed consider Komondor 23

Komondor public class Komondor extends PureBreed { private final String BREED = "komondor"; public Komondor() { super(breed); public Komondor(int size, int energy) { super(breed, size, energy); // other Komondor methods... 24

Another example: Tetris played with 7 standard blocks called tetriminoes blocks drop from the top player can move blocks left, right, and down player can spin blocks left and right 25

Tetriminoes spinning the I, J, and S blocks 26

Tetriminoes features common to all tetriminoes has-a color has-a shape has-a position draw move left, right, and down features unique to each kind of tetrimino the actual shape spin left and right 27

Block - color : Color - position : Point2 - grid : BlockGrid # Block(int, Point2, Color) + draw() + movedown() + moveleft() + moveright()... class name in italics for abstract classes a 2D point a grid object that stores the shape protected constructor Block is abstract because we can't define the shape of a generic block IBlock + IBlock(Point2, Color) + spinleft() + spinright() constructor defines the shape methods modify the shape to produce the rotated version of the block 28 http://www.eecs.yorku.ca/course_archive/2016-17/f/2030/labs/lab4/lab4.html

Inheritance (cont) Static Features 29

Static Fields and Inheritance static fields behave the same as non-static fields in inheritance public and protected static fields are inherited by subclasses, and subclasses can access them directly by name private static fields are not inherited and cannot be accessed directly by name but they can be accessed/modified using public and protected methods 30

Static Fields and Inheritance the important thing to remember about static fields and inheritance there is only one copy of the static field shared among the declaring class and all subclasses consider trying to count the number of Dog objects created by using a static counter 31

// the wrong way to count the number of Dogs created public abstract class Dog { // other fields... static protected int numcreated = 0; Dog() { //... Dog.numCreated++; public static int getnumbercreated() { return Dog.numCreated; protected, not private, so that subclasses can modify it directly // other contructors, methods... 32

// the wrong way to count the number of Dogs created public class Mix extends Dog { // fields... Mix() { super(); Mix.numCreated++; // other contructors, methods... 33

// too many dogs! public class TooManyDogs { public static void main(string[] args) { Mix mutt = new Mix(); System.out.println( Mix.getNumberCreated() ); prints 2 34

What Went Wrong? there is only one copy of the static field shared among the declaring class and all subclasses Dog declared the static field Dog increments the counter every time its constructor is called Mix inherits and shares the single copy of the field Mix constructor correctly calls the superclass constructor which causes numcreated to be incremented by Dog Mix constructor then incorrectly increments the counter 35

Counting Dogs and Mixes suppose you want to count the number of Dog instances and the number of Mix instances Mix must also declare a static field to hold the count somewhat confusingly, Mix can give the counter the same name as the counter declared by Dog 36

public class Mix extends Dog { // other fields... private static int numcreated = 0; // bad style; hides Dog.numCreated public Mix() { super(); // will increment Dog.numCreated // other Mix stuff... numcreated++; // will increment Mix.numCreated //... 37

Hiding Fields note that the Mix field numcreated has the same name as an field declared in a superclass whenever numcreated is used in Mix, it is the Mix version of the field that is used if a subclass declares an field with the same name as a superclass field, we say that the subclass field hides the superclass field considered bad style because it can make code hard to read and understand should change numcreated to nummixcreated in Mix 38

Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there is no dynamic dispatch on static methods therefore, you cannot override a static method 39

public abstract class Dog { private static int numcreated = 0; public static int getnumcreated() { return Dog.numCreated; public class Mix { private static int nummixcreated = 0; public static int getnumcreated() { return Mix.numMixCreated; notice no @Override public class Komondor { private static int numkomondorcreated = 0; public static int getnumcreated() { return Komondor.numKomondorCreated; notice no @Override 40

public class WrongCount { public static void main(string[] args) { Dog mutt = new Mix(); Dog shaggy = new Komondor(); System.out.println( mutt.getnumcreated() ); System.out.println( shaggy.getnumcreated() ); System.out.println( Mix.getNumCreated() ); System.out.println( Komondor.getNumCreated() ); Dog version Dog version Mix version Komondor version prints 2 2 1 1 41

What's Going On? there is no dynamic dispatch on static methods because the declared type of mutt is Dog, it is the Dog version of getnumcreated that is called because the declared type of shaggy is Dog, it is the Dog version of getnumcreated that is called 42

Hiding Methods notice that Mix.getNumCreated and Komondor.getNumCreated work as expected if a subclass declares a static method with the same name as a superclass static method, we say that the subclass static method hides the superclass static method you cannot override a static method, you can only hide it hiding static methods is considered bad form because it makes code hard to read and understand 43

the client code in WrongCount illustrates two cases of bad style, one by the client and one by the implementer of the Dog hierarchy 1. the client should not have used an instance to call a static method 2. the implementer should not have hidden the static method in Dog 44

45 Using superclass methods

Other Methods methods in a subclass will often need or want to call methods in the immediate superclass a new method in the subclass can call any public or protected method in the superclass without using any special syntax a subclass can override a public or protected method in the superclass by declaring a method that has the same signature as the one in the superclass a subclass method that overrides a superclass method can call the overridden superclass method using the super keyword 46

Dog equals we will assume that two Dogs are equal if their size and energy are the same @Override public boolean equals(object obj) { boolean eq = false; if(obj!= null && this.getclass() == obj.getclass()) { Dog other = (Dog) obj; eq = this.getsize() == other.getsize() && return eq; this.getenergy() == other.getenergy(); 47

Mix equals (version 1) two Mix instances are equal if their Dog subobjects are equal and they have the same breeds @Override public boolean equals(object obj) { // the hard way boolean eq = false; if(obj!= null && this.getclass() == obj.getclass()) { Mix other = (Mix) obj; eq = this.getsize() == other.getsize() && return eq; this.getenergy() == other.getenergy() && this.breeds.size() == other.breeds.size() && this.breeds.containsall(other.breeds); subclass can call public method of the superclass 48

Mix equals (version 2) two Mix instances are equal if their Dog subobjects are equal and they have the same breeds Dog equals already tests if two Dog instances are equal Mix equals can call Dog equals to test if the Dog subobjects are equal, and then test if the breeds are equal also notice that Dog equals already checks that the Object argument is not null and that the classes are the same Mix equals does not have to do these checks again 49

@Override public boolean equals(object obj) { boolean eq = false; if (super.equals(obj)) { // the Dog subobjects are equal Mix other = (Mix) obj; eq = this.breeds.size() == other.breeds.size() && return eq; subclass method that overrides a superclass method can call the original superclass method this.breeds.containsall(other.breeds); 50

Dog tostring @Override public String tostring() { String s = "size " + this.getsize() + "energy " + this.getenergy(); return s; 51

Mix tostring @Override public String tostring() { StringBuffer b = new StringBuffer(); b.append(super.tostring()); for(string s : this.breeds) b.append(" " + s); b.append(" mix"); return b.tostring(); size and energy of the dog breeds of the mix 52

Dog hashcode // similar to code generated by Eclipse @Override public int hashcode() { final int prime = 31; int result = 1; result = prime * result + this.getenergy(); result = prime * result + this.getsize(); return result; use this.energy and this.size to compute the hash code 53

Mix hashcode // similar to code generated by Eclipse @Override public int hashcode() { final int prime = 31; int result = super.hashcode(); result = prime * result + this.breeds.hashcode(); return result; use this.energy, this.size, and this.breeds to compute the hash code 54

Graphical User Interfaces notes Chap 7 55

Java Swing Swing is a Java toolkit for building graphical user interfaces (GUIs) http://docs.oracle.com/javase/tutorial/uiswing/toc.html old version of the Java tutorial had a visual guide of Swing components http://web.mit.edu/6.005/www/sp14/psets/ps4/java-6- tutorial/components.html 56

Simple Applications simple applications often consist of just a single window (containing some controls) JFrame window with border, title, buttons 57

Simple Applications simple applications can be implemented as a subclass of a JFrame hundreds of inherited methods but only a dozen or so are commonly called by the implementer (see URL below) Object Component Container Window Frame JFrame user interface item holds other components plain window window with title and border View 58 https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html

Simple Applications a simple application made up of a: JFrame has-a JMenuBar has-a Container (called the content pane) has-a JLabel 59

Simple Applications a simple application made up of a: JFrame has-a JMenuBar has-a Container (called the content pane) has-a JLabel 60

Creating JFrames 1. Create the frame 2. Choose what happens when the frame closes 3. Create components and put them in the frame 4. Size the frame 5. Show it 61

public class ImageViewer extends JFrame implements ActionListener { // a unique identifier to associate with the Open command public static final String OPEN_COMMAND = "Open"; // a label to show the image private JLabel img; public ImageViewer() { // 1. Create the frame super("image Viewer"); // 2. Choose what happens when the frame closes this.setdefaultcloseoperation(jframe.exit_on_close); // 3. Create components and put them in the frame this.makemenu(); this.makelabel(); this.setlayout(new FlowLayout()); // 4. Size the frame this.setminimumsize(new Dimension(600, 400)); this.pack(); // 5. Show it this.setvisible(true); 62

public class ImageViewer extends JFrame implements ActionListener { // a unique identifier to associate with the Open command public static final String OPEN_COMMAND = "Open"; // a label to show the image private JLabel img; public ImageViewer() { // 1. Create the frame super("image Viewer"); // 2. Choose what happens when the frame closes this.setdefaultcloseoperation(jframe.exit_on_close); // 3. Create components and put them in the frame this.makemenu(); this.makelabel(); this.setlayout(new FlowLayout()); // 4. Size the frame this.setminimumsize(new Dimension(600, 400)); this.pack(); // 5. Show it this.setvisible(true); 63

public class ImageViewer extends JFrame implements ActionListener { // a unique identifier to associate with the Open command public static final String OPEN_COMMAND = "Open"; // a label to show the image private JLabel img; public ImageViewer() { // 1. Create the frame super("image Viewer"); // 2. Choose what happens when the frame closes this.setdefaultcloseoperation(jframe.exit_on_close); // 3. Create components and put them in the frame this.makemenu(); this.makelabel(); this.setlayout(new FlowLayout()); // 4. Size the frame this.setminimumsize(new Dimension(600, 400)); this.pack(); // 5. Show it this.setvisible(true); 64

public class ImageViewer extends JFrame implements ActionListener { // a unique identifier to associate with the Open command public static final String OPEN_COMMAND = "Open"; // a label to show the image private JLabel img; to respond to the user selecting the Open command from the menu public ImageViewer() { // 1. Create the frame super("image Viewer"); // 2. Choose what happens when the frame closes this.setdefaultcloseoperation(jframe.exit_on_close); // 3. Create components and put them in the frame this.makemenu(); this.makelabel(); this.setlayout(new FlowLayout()); // 4. Size the frame this.setminimumsize(new Dimension(600, 400)); this.pack(); // 5. Show it this.setvisible(true); controls how the components re-size and re-position when the JFrame changes size 65

public class ImageViewer extends JFrame implements ActionListener { // a unique identifier to associate with the Open command public static final String OPEN_COMMAND = "Open"; // a label to show the image private JLabel img; public ImageViewer() { // 1. Create the frame super("image Viewer"); // 2. Choose what happens when the frame closes this.setdefaultcloseoperation(jframe.exit_on_close); // 3. Create components and put them in the frame this.makemenu(); this.makelabel(); this.setlayout(new FlowLayout()); // 4. Size the frame this.setminimumsize(new Dimension(600, 400)); this.pack(); // 5. Show it this.setvisible(true); sizes the JFrame so that all components have their preferred size; uses the layout manager to help adjust component sizes 66

public class ImageViewer extends JFrame implements ActionListener { // a unique identifier to associate with the Open command public static final String OPEN_COMMAND = "Open"; // a label to show the image private JLabel img; public ImageViewer() { // 1. Create the frame super("image Viewer"); // 2. Choose what happens when the frame closes this.setdefaultcloseoperation(jframe.exit_on_close); // 3. Create components and put them in the frame this.makemenu(); this.makelabel(); this.setlayout(new FlowLayout()); // 4. Size the frame this.setminimumsize(new Dimension(600, 400)); this.pack(); // 5. Show it this.setvisible(true); 67

Labels a label displays unselectable text and images label JLabel label JLabel 68 http://docs.oracle.com/javase/tutorial/uiswing/components/label.html

private void makelabel() { this.img = new JLabel(""); this.getcontentpane().add(this.img); 69

Menus a menu appears in a menu bar (or a popup menu) each item in the menu is a menu item menu JMenu menu item JMenuItem menu bar JMenuBar JMenuBar + add(jmenu) * JMenu * + add(jmenuitem) JMenuItem 70 http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html

Menus to create a menu create a JMenuBar create one or more JMenu objects add the JMenu objects to the JMenuBar create one or more JMenuItem objectes add the JMenuItem objects to the JMenu 71

private void makemenu() { JMenuBar menubar = new JMenuBar(); JMenu filemenu = new JMenu("File"); menubar.add(filemenu); JMenuItem openmenuitem = new JMenuItem("Open..."); openmenuitem.setactioncommand(imageviewer.open_command); openmenuitem.addactionlistener(this); filemenu.add(openmenuitem); this.setjmenubar(menubar); 72

private void makemenu() { JMenuBar menubar = new JMenuBar(); JMenu filemenu = new JMenu("File"); menubar.add(filemenu); JMenuItem openmenuitem = new JMenuItem("Open..."); openmenuitem.setactioncommand(imageviewer.open_command); openmenuitem.addactionlistener(this); filemenu.add(openmenuitem); this.setjmenubar(menubar); 73

private void makemenu() { JMenuBar menubar = new JMenuBar(); JMenu filemenu = new JMenu("File"); menubar.add(filemenu); JMenuItem openmenuitem = new JMenuItem("Open..."); openmenuitem.setactioncommand(imageviewer.open_command); openmenuitem.addactionlistener(this); filemenu.add(openmenuitem); this.setjmenubar(menubar); to respond to the user selecting the Open command from the menu 74

private void makemenu() { JMenuBar menubar = new JMenuBar(); JMenu filemenu = new JMenu("File"); menubar.add(filemenu); JMenuItem openmenuitem = new JMenuItem("Open..."); openmenuitem.setactioncommand(imageviewer.open_command); openmenuitem.addactionlistener(this); filemenu.add(openmenuitem); this.setjmenubar(menubar); 75

Event Driven Programming so far we have a frame with some UI elements (menu, menu item, label) now we need to implement the actions each UI element is a source of events button pressed, slider moved, text changed, etc. when the user interacts with a UI element an event is triggered this causes an event object to be sent to every object listening for that particular event the event object carries information about the event the event listeners respond to the event 76

Not a UML Diagram event listener A event source 1 event object 1 event listener B event listener C event source 2 event object 2 event listener D 77

Implementation each JMenuItem has two inherited methods from AbstractButton public void addactionlistener(actionlistener l) public void setactioncommand(string actioncommand) for the JMenuItem 1. call addactionlistener with the listener as the argument 2. call setactioncommand with a string describing what event has occurred 78

Implementation our application has one event thiat is fired by a button (JMenuItem) a button fires an ActionEvent event whenever it is clicked ImageViewer listens for fired ActionEvents how? by implementing the ActionListener interface public interface ActionListener { void actionperformed(actionevent e); 79

@Override public void actionperformed(actionevent e) { String command = e.getactioncommand(); if (command.equals(imageviewer.open_command)) { JFileChooser chooser = new JFileChooser(); int result = chooser.showopendialog(this); if (result == JFileChooser.APPROVE_OPTION) { String filename = chooser.getselectedfile().getabsolutepath(); ImageIcon icon = new ImageIcon(fileName); if (icon.getimageloadstatus() == MediaTracker.COMPLETE) { this.img.seticon(icon); this.pack(); 80

@Override public void actionperformed(actionevent e) { String command = e.getactioncommand(); if (command.equals(imageviewer.open_command)) { JFileChooser chooser = new JFileChooser(); int result = chooser.showopendialog(this); if (result == JFileChooser.APPROVE_OPTION) { String filename = to respond to the user selecting the Open command from the menu chooser.getselectedfile().getabsolutepath(); ImageIcon icon = new ImageIcon(fileName); if (icon.getimageloadstatus() == MediaTracker.COMPLETE) { this.img.seticon(icon); this.pack(); 81

@Override public void actionperformed(actionevent e) { String command = e.getactioncommand(); if (command.equals(imageviewer.open_command)) { JFileChooser chooser = new JFileChooser(); int result = chooser.showopendialog(this); if (result == JFileChooser.APPROVE_OPTION) { String filename = used to pick the file to open chooser.getselectedfile().getabsolutepath(); ImageIcon icon = new ImageIcon(fileName); if (icon.getimageloadstatus() == MediaTracker.COMPLETE) { this.img.seticon(icon); this.pack(); 82

@Override public void actionperformed(actionevent e) { String command = e.getactioncommand(); if (command.equals(imageviewer.open_command)) { JFileChooser chooser = new JFileChooser(); int result = chooser.showopendialog(this); if (result == JFileChooser.APPROVE_OPTION) { String filename = chooser.getselectedfile().getabsolutepath(); ImageIcon icon = new ImageIcon(fileName); if (icon.getimageloadstatus() == MediaTracker.COMPLETE) { this.img.seticon(icon); this.pack(); show the file chooser and get the user result (ok or cancel) 83

@Override public void actionperformed(actionevent e) { String command = e.getactioncommand(); if (command.equals(imageviewer.open_command)) { JFileChooser chooser = new JFileChooser(); int result = chooser.showopendialog(this); if (result == JFileChooser.APPROVE_OPTION) { String filename = chooser.getselectedfile().getabsolutepath(); ImageIcon icon = new ImageIcon(fileName); if (icon.getimageloadstatus() == MediaTracker.COMPLETE) { this.img.seticon(icon); this.pack(); user picked a file and pressed ok 84

@Override public void actionperformed(actionevent e) { String command = e.getactioncommand(); if (command.equals(imageviewer.open_command)) { JFileChooser chooser = new JFileChooser(); int result = chooser.showopendialog(this); if (result == JFileChooser.APPROVE_OPTION) { String filename = chooser.getselectedfile().getabsolutepath(); ImageIcon icon = new ImageIcon(fileName); if (icon.getimageloadstatus() == MediaTracker.COMPLETE) { this.img.seticon(icon); this.pack(); get the file name and directory path that the user picked 85

@Override public void actionperformed(actionevent e) { String command = e.getactioncommand(); if (command.equals(imageviewer.open_command)) { JFileChooser chooser = new JFileChooser(); int result = chooser.showopendialog(this); if (result == JFileChooser.APPROVE_OPTION) { String filename = chooser.getselectedfile().getabsolutepath(); ImageIcon icon = new ImageIcon(fileName); if (icon.getimageloadstatus() == MediaTracker.COMPLETE) { this.img.seticon(icon); this.pack(); try to read the image 86

@Override public void actionperformed(actionevent e) { String command = e.getactioncommand(); if (command.equals(imageviewer.open_command)) { JFileChooser chooser = new JFileChooser(); int result = chooser.showopendialog(this); if (result == JFileChooser.APPROVE_OPTION) { String filename = chooser.getselectedfile().getabsolutepath(); ImageIcon icon = new ImageIcon(fileName); if (icon.getimageloadstatus() == MediaTracker.COMPLETE) { this.img.seticon(icon); this.pack(); if the image was successfully read from disk 87

@Override public void actionperformed(actionevent e) { String command = e.getactioncommand(); if (command.equals(imageviewer.open_command)) { JFileChooser chooser = new JFileChooser(); int result = chooser.showopendialog(this); if (result == JFileChooser.APPROVE_OPTION) { String filename = chooser.getselectedfile().getabsolutepath(); ImageIcon icon = new ImageIcon(fileName); if (icon.getimageloadstatus() == MediaTracker.COMPLETE) { this.img.seticon(icon); this.pack(); set the label image and re-size the frame 88

public static void main(string[] args) { // make an ImageViewer instance new ImageViewer(); 89