ITI 1221. Introduction to Computing II Lab-7 Dewan Tanvir Ahmed University of Ottawa.

Slides:



Advertisements
Similar presentations
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Advertisements

Written by: Dr. JJ Shepherd
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Chapter 10: Inheritance and Polymorphism
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Stacks, Queues, and Deques
Io package as Java’s basic I/O system continue’d.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Topic 3 The Stack ADT.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Java Programming: Guided Learning with Early Objects
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki
ITI Introduction to Computing II Lab-6 Dewan Tanvir Ahmed University of Ottawa.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 Stacks and Queues Based on D.S. Malik, Java Programming: Program Design Including Data Structures.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Written by: Dr. JJ Shepherd
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Classes Revisited Chapter 8.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Lesson 28: More on the GUI button, frame and actions.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Last Revision. Question1 Novice Java programmers often write code similar to, class C { public int x;... }... C[] a = new C[10]; for(int i = 0; i < a.length;
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
The need for Programming Languages
Chapter 14 – Exception Handling
Queues Rem Collier Room A1.02
Chapter 11: Inheritance and Polymorphism
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
CS 302 Week 11 Jim Williams, PhD.
Queues 11/16/2018 4:19 AM Queues 11/16/2018 4:19 AM Queues.
Constructors, GUI’s(Using Swing) and ActionListner
ITI Introduction to Computing II Lab-12
Stacks, Queues, and Deques
Presentation transcript:

ITI Introduction to Computing II Lab-7 Dewan Tanvir Ahmed University of Ottawa

Today’s Objective  Understanding the current Assignment, e.g. Assignment 3  Reviewing the solution of Assignment 2  Reviewing the solution of Mid term  GUI and Event Driven Programming

Assignment 3  Objectives oFurther understanding of exception handling in Java oLearn about two implementations of Queues oIntroduction to Queue-based algorithms  Breath-First Search (BFS) algorithm

Assignment 3 (cont..) Exceptions oCreate a new exception type called EmptyQueueException  A subclass of RuntimeException  The class EmptyQueueException has two constructors –A default constructor with no parameters –A constructor with a parameter of type String, »which is used to save a reference to an error message for later retrieval by the getMessage method

Assignment 3 (cont..) Exceptions oCreate a new exception type called QueueOverflowException  A subclass of RuntimeException  The class QueueOverflowException has two constructors –A default constructor with no parameters –A constructor with a parameter of type String, which is used to save a reference to an error message for later retrieval by the getMessage method

Assignment 3 (cont..) Exceptions omodify the methods of the classes LinkedQueue and CircularQueue  To validate the pre-conditions and  throw the appropriate exception when needed: –EmptyQueueException, –QueueOverflowException and –IllegalArgumentException

Assignment 3 (cont..) Copy oThe method copy() creates a duplicate of a queue containing the same elements and be in the same order oIt creates a copy of a queue such that the values of the queue and its copy are shared, Shallow copy. oClass LinkedQueue: public LinkedQueue copy()  Adding elements to a linked structure having a front reference and rear reference  You can’t use the instance methods of this class to implement this method  NB. Two queues are sharing the values but not the nodes oClass public CircularQueue copy()  Exercise of wrapping front and rear around the boundaries  You can’t use the instance methods of this class to implement this method  The elements of the duplicate should be stored at positions 0 to size - 1

Assignment 3 (cont..) public boolean equals( Object other ) Override the method public boolean equals( Object other )  It returns –true if other designates a Queue (any implementation of the interface Queue) that contains the same number of elements as this queue, and each element of the other queue must be “equals” to the corresponding element in this queue –false otherwise  Both queues must not be changed by the method equals, i.e. before and after a call to the method equals, this and the other queue must contain the same elements, in the same order

Assignment 3 (cont..) Test oWrite a Test program for the methods copy and equals of the classes  LinkedQueue and  CircularQueue.

Assignment 3 (cont..)  Questions??? (LinkedQueue, CircularQueue)  Size  Wrapping  Enqueue  Dequeue  Empty!  Full!

Assignment 3, Part II  Queue Based Algorithms oBFS

Assignment 3, Part II (cont..)  Class HTML oHTML document = new HTML( " ); int count=0; while ( document.hasMoreUrls() ) { String url = document.nextUrl(); count++; } System.out.println( "This document has " + count + " links." ); oHow to get the content  document.getPage();

Assignment 3, Part II (cont..)  Class Solution oA Solution has two instance variables (both of type String).  One that designates the path represented by the solution.  The other stores the last URL of the path represented by the solution; oConstructors  The constructor Solution( String lastUrl ) –sets both instance variables to lastUrl.  The constructor Solution( Solution partial, String lastUrl ) –sets the path of this Solution to that of partial concatenated with lastUrl; –path = partial.getpath() -> lastUrl  It also sets the instance variable for the last URL of this object to lastUrl; oA solution has two access methods,  getPath and  getLasUrl

Assignment 3, Part II (cont..) Crawler oThe class Crawler contains three static methods that are used to find a path from a Web page A to a Web page B oprivate static boolean isValid( String url )  returns true –if url is a well formed URL designating an existing/readable Web page, and false otherwise. Use the fact that the constructor of an HTML object  Throws an exception, of type MalformedURLException, –if the url is not well formed  Throws an exception, of type IOException, –if the content of the page cannot be successfully read oAny Question?

Assignment 3, Part II (cont..) Crawler oprivate static Solution solve( String a, String b )  Implement a breath-first search algorithm for finding a path from a Web page A to a Web page B.  The breath-first search uses a Queue data structure (this can be your own implementation of LinkedQueue)  The algorithm initializes the queue to contain just the partial solution that consists of the Web page A only, and repeatedly does the following: –dequeues a partial solution off the queue; –extend the partial solution by one URL in all possible ways –enqueues each of the “valid” extension

Assignment 3, Part II (cont..) Crawler opublic static void main( String[] args )  The main method prints the following message unless there are exactly two arguments on the command line, and exists immediately –Usage: java Crawler src dst  If the command line has two arguments, those arguments are used for calling the method solve  The main method prints the path if it exists, and “no path” if no such path was found

Solution – Assignment 2  Let’s Go oClick hereClick here

Mid-Term Solution - Q1

 Part A oImplement the three classes, as well as the interface Player.  Make sure to include the constructors  For each attribute –write the access methods –The values of the attributes must be valid »If the value of the parameter is less than 0.0 then set the value of the attribute to 0.0 »Similarly, if the value of the parameter is larger than the upper limit then set the attribute to its upper limit  Finally, implement the methods attack Mid-Term Solution Q1 (cont..)

Implementation of interface Player: oAll players of the game have a method double attack() that returns a value representing the strength of the attack. oPlayer is an interface declaring the method double attack() public interface Player { public abstract double attack(); } Mid-Term Solution Q1 (cont..)

Implementation of abstract class AbstractPlayer: oAn AbstractPlayer defines the characteristics that are common to all the creatures oThis abstract class implements the interface Player oAll the creatures have  A name (a character String)  A life meter (a double ranging from 0.0 to 100.0) –The initial value of the life meter is 50.0 oImplement constructor method oImplement access methods  getters and setter methods for attributes name and life meter Mid-Term Solution Q1 (cont..)

public abstract class AbstractPlayer implements Player { private static final double LIFE_METER_INIT = 50.0; private static final double LIFE_METER_MAX = 100.0; private static final double LIFE_METER_MIN = 0.0; private String name; private double lifeMeter; public AbstractPlayer( String name ) { lifeMeter = LIFE_METER_INIT; this.name = name; } public String getName() { return name; } public String setName( String name ) { this.name = name; } public double getLifeMeter() { return lifeMeter; } Mid-Term Solution Q1 (cont..)

public void setLifeMeter( double value ) { lifeMeter = value; if ( lifeMeter < LIFE_METER_MIN ) { lifeMeter = LIFE_METER_MIN; } else if ( lifeMeter > LIFE_METER_MAX ) { lifeMeter = LIFE_METER_MAX; } Mid-Term Solution Q1 (cont..)

Class Uldra oAn Uldra is a creature (player) that carries a bottle filled with poison (a double value in the range ) oUldra creatures have a tendency to misplace their bottles (a boolean value indicates if this Uldra has or not its bottle) oThe strength of an attack is zero if the Uldra has no bottle. Otherwise, the strength of an attack is 10.0, or the remaining amount of poison (which ever value is smaller) oThe strength of the attack reduces the quantity of poison left by the same amount Mid-Term Solution Q1 (cont..)

public class Uldra extends AbstractPlayer { private boolean hasABottle; private double poison; public Uldra( String name ) { super( name ); hasABottle = false; poison = 0.0; } public boolean hasABottle() { return hasABottle; } public void setHasBottle( boolean value ) { hasABottle = value; if ( ! hasABottle ) { poison = 0.0; } public double getPoison() { return poison; } Mid-Term Solution Q1 (cont..)

public void setPoison( double value ) { if ( hasABottle ) { poison = value; if ( poison < 0.0 ) { poison = 0.0; } else if ( poison > ) { poison = 100.0; } public double attack() { double result = 10.0; if ( ! hasABottle ) { result = 0; } else if ( getPoison() < result ) { result = getPoison(); } setPoison( getPoison() - result ); return result; } Mid-Term Solution Q1 (cont..)

Class Yakku oYakku creatures have magical powers (double, range , the initial value is 10.0) oThe strength of the attack depends on both its life meter and its magical powers. Specifically, a weight w is calculated as being the value of the life meter divided by 10.0 oThe weight w is then multiplied by the level of magical powers to obtain the strength of the attack oAn attack reduces both the life meter and the magical powers by the strength of the attack. Mid-Term Solution Q1 (cont..)

public class Yakku extends AbstractPlayer { private static final double MAGIC_POWERS_MAX = 100.0; private static final double MAGIC_POWERS_MIN = 0.0; private static final double MAGIC_POWERS_INIT = 40.0; private double magicPowers = MAGIC_POWERS_INIT; public Yakku( String name ) { super( name ); } public double getMagicPowers() { return magicPowers; } public void setMagicPowers( double value ) { magicPowers = value; if ( magicPowers < MAGIC_POWERS_MIN) { magicPowers = MAGIC_POWERS_MIN; } else if ( magicPowers > MAGIC_POWERS_MAX ) { magicPowers = MAGIC_POWERS_MAX; } Mid-Term Solution Q1 (cont..)

public double attack() { double w = getLifeMeter() / 10.0; double result = w * magicPowers; setLifeMeter( getLifeMeter() - result ); magicPowers = magicPowers - result; return result; } Mid-Term Solution Q1 (cont..)

Part B oWrite a polymorphic class method, duel, that has two parameters, both of type AbstractPlayer, first and second. oRules  While both players are alive (i.e. their life meter is greater than zero)  The first player launches an attack onto the second one  If the second player is still alive, it launches an attack onto the first player  When a player “a” launches an attack onto a player “b”, you must reduce the value of the life meter of “b” by a.attack()  Finally, the method displays the name of the player that is still alive Mid-Term Solution Q1 (cont..)

public static void duel( AbstractPlayer first, AbstractPlayer second ) { while ( first.getLifeMeter() > 0.0 && second.getLifeMeter() > 0.0 ) { double strength; strength = first.attack(); second.setLifeMeter( second.getLifeMeter() - strength ); if ( second.getLifeMeter() > 0.0 ) { strength = second.attack(); first.setLifeMeter( first.getLifeMeter() - strength ); } AbstractPlayer alive = first; if ( second.getLifeMeter() > 0.0 ) { alive = second; } System.out.println( alive.getName() + " is alive!" ); } Mid-Term Solution Q1 (cont..)

Calculator c = new Calculator(); c.execute( " ~ print + print ^ print * print - print" ); -top- INTEGER: -1 INTEGER: 4 INTEGER: 2 INTEGER: 5 INTEGER: 40 -bottom- -top- INTEGER: 3 INTEGER: 2 INTEGER: 5 INTEGER: 40 -bottom- -top- INTEGER: 8 INTEGER: 5 INTEGER: 40 -bottom- -top- INTEGER: 40 -bottom- -top- INTEGER: 0 -bottom Mid-Term Solution Q2

 Correct at least 5 mistakes (logic, runtime or compile-time errors) in the partial implementation  "implements Stack" missing  constructor odeclaration of a local variable elems masks the instance variable elem o’capacity = capacity’ should be o’this.capacity = capacity’, otherwise, the instance variable capacity will not be initialized othis.increment not assigned  increaseSize oneeds a for loop to copy the elements or System.arraycopy  Pop oshould decrease size then access the element o"return saved" missing o(should be calling decreaseSize after removing the element. ) Mid-Term Solution Q3

 Complete the partial implementation of the class DynamicArrayStack public void push( Object element ) { if (size == elems.length) { increaseSize(); } elems[ size ] = element; size = size + 1; } Mid-Term Solution Q3 (cont..)

 Complete the partial implementation of the class DynamicArrayStack private void increaseSize() { Object[] newElems; newElems = new Object[elems.length + increment]; // Copying all the elements to the new array newElems = elems; // Replacing elems with the new and larger array elems = newElems; } Mid-Term Solution Q3 (cont..)

 Complete the partial implementation of the class DynamicArrayStack public Object pop() { size = size - 1; Object saved = elems[ size ]; // Scrubbing the memory! elems[ size ] = null; if (elems.length > capacity && ( elems.length - size ) >= increment) { decreaseSize(); } return saved; } Mid-Term Solution Q3 (cont..)

private void decreaseSize() { int newSize = elems.length - increment; if ( newSize < capacity ) { newSize = capacity; } Object[] newElems; newElems = new Object[ newSize ]; for ( int i=0; i<size; i++ ) { newElems[ i ] = elems[ i ]; } // Replacing elems with the new/smaller array elems = newElems; } Mid-Term Solution Q3 (cont..)  Complete the partial implementation of the class DynamicArrayStack

 In the class CombinationLock, override the method equals. oTwo locks are equals if  Their status are “equals” and both CombinationLock have the same combination (defined by the variables first, second and third)  Otherwise, the method returns false oNo values are considered illegal; in particular, the method should be handling null values. Mid-Term Solution Q4

public boolean equals( Object obj ) { if ( obj == null || ! ( obj instanceof CombinationLock ) ) return false; CombinationLock other = (CombinationLock) obj; boolean result = true; if ( first != other.first ) result = false; else if ( second != other.second ) result = false; else if ( third != other.third ) result = false; else if ( status == null ) result = ( other.status == null ); else result = status.equals( other.status ); return result; } Mid-Term Solution Q5 (cont..)

 LinkedPair - Part A  Draw the memory diagram representing the content of the memory after the execution of the following statement Pair p = new LinkedPair ( new Name("Joseph", "Rotblat"), new Name("Wangari", "Maathai")); Mid-Term Solution Q6

 LinkedPair - Part B  For the partial implementation of the class LinkedPair, write the instance method public sort() that sorts the (two) elements of a LinkedPair  Rules oChange the order of the elements (objects of the class Elem) oexchanging the values of the nodes is not acceptable. Mid-Term Solution Q5 (cont..) public void sort() { if ( first.value.compareTo( first.next.value ) > 0 ) { Elem newFirst = first.next; newFirst.next = first; first.next = null; first = newFirst; }

 Part C  Complete the implementation of the method String toString(). It returns a String representation of the pair ostarting with “(” oFollowed by the String representation of the first object of the pair oFollowed by “,” oFollowed by the String representation of the second object of the pair oFollowed by “)”. public String toString() { return "(" + first.value + "," + first.next.value + ")"; } Mid-Term Solution Q5 (cont..)

 Part A oDefine a new checked exception called ZendaIOException. oThis should be a specialized IOException. public class ZendaIOException extends IOException { public ZendaIOException() { super(); } public ZendaIOException( String message ) { super( message ); } Mid-Term Solution Q6

Mid-Term Solution Q6 (cont..) import java.io.FileInputStream; import java.io.FileNotFoundException; public class Zenda { private static void getConfig( String name ) throws ZendaIOException { if ( name == null ) { throw new IllegalArgumentException( "null value" ); } FileInputStream input; try { input = new FileInputStream( name ); } catch ( FileNotFoundException e ) { throw new ZendaIOException( "file not found: " + name ); }

Mid-Term Solution Q6 (cont..) private static void init() throws ZendaIOException{ getConfig( "config.dat" ); } public static void main( String[] args ) { try { init(); } catch ( ZendaIOException e ) { System.err.println( "ERROR READING CONFIG FILE" ); e.printStackTrace(); System.exit( 1 ); }

 Part C oExplain why a runtime exception will occur if the following statements are executed. public class Manager { private Object[] elems; public Manager( int capacity ) { if ( elems.length == 0 ) { elems = new Object[ capacity ]; } public static void main( String[] args ) { Manager m = new Manager( 100 ); } Mid-Term Solution (cont..) NullPointerException?

GUI and Event Driven Programming  Any component can be the source of an event oA button generates an event when you click on it.  Any class can be a listener for an event oIt simply implements the method (s) of the interface  The object that handles the event generated from the click of a button needs to implement the interface ActionListener.  The object that handles the event generated when a window is closed must implement the interface WindowListener.

GUI and Event Driven Programming (cont..)  The event generated by the source component is sent to the listeners who registered with the component.  The source has a method addActionListener who needs as a parameter an object that implements the interface ActionListener.  Since the handler implements the interface ActionListener, the source knows that the handler has a method actionPerformed(...).  Example oprivate DisplayArea display = new DisplayArea(); obutton.addActionListener(display); Source Listener Object Registration

GUI and Event Driven Programming (cont..) import java.awt.*; import java.awt.event.*; public class GUI extends Frame { private Button bLeft = new Button("Left"); private Button bRight = new Button("Right"); private DisplayArea display = new DisplayArea(); public GUI() { super("DGD - Week 8"); setBackground(Color.WHITE); add(display, BorderLayout.CENTER); Panel p = new Panel(); p.add(bLeft); p.add(bRight); add(p, BorderLayout.SOUTH);

GUI and Event Driven Programming (cont..) bLeft.addActionListener(display); bRight.addActionListener(display); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } ); pack(); show(); } public static void main(String[] args) { new GUI(); }

GUI and Event Driven Programming (cont..) import java.awt.*; import java.awt.event.*; class DisplayArea extends Canvas implements ActionListener { private Point center; DisplayArea() { setSize(200,200); center = new Point(100,100); } public void paint(Graphics g) { g.setColor(Color.RED); g.fillOval(center.x - 5, center.y - 5, 10, 10); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Left")) { center.x = (center.x + 190) % 200; // subtracts 10 } else if (cmd.equals("Right")) { center.x = (center.x + 10) % 200; } repaint(); }

WindowAdapter  A Frame has a method addWindowListener that allows you to register an object that implements the interface WindowListener.  The interface lists 7 methods: opublic void windowOpened(WindowEvent e); opublic void windowClosing(WindowEvent e); opublic void windowClosed(WindowEvent e); opublic void windowIconified(WindowEvent e); opublic void windowDeiconified(WindowEvent e); opublic void windowActivated(WindowEvent e); opublic void windowDeactivated(WindowEvent e);  Still, in order to register a handler with the frame we have to provide an object that implements this interface, owhich means that we have to implement the 7 methods

Solution - WindowAdapter Solution - 1: All the methods are empty except for windowClosing: import java.awt.event.*; class MyWindowListener implements WindowListener { public void windowOpened(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowClosing(WindowEvent e) { System.exit(0); } public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }

Solution - WindowAdapter Solution -2 1.Inherit all the empty methods and 2.implements the ones we need for this application. class MyWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); }

The End