1 Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes). A nested class.

Slides:



Advertisements
Similar presentations
1 Nested and Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes).
Advertisements

Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
1 Review of classes and subclasses M fast through this material, since by now all have seen it in CS100 or the Java bootcamp First packages Then classes.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
For IST410 Students only Events-1 Event Handling.
Unit 12 Object-oriented programming: Event-driven programming for GUI Jin Sa.
1 What’s a class People are confused with nested classes and anonymous classes. Experiments in a recitation last week revealed that the problems were probably.
Lecture 19 Graphics User Interfaces (GUIs)
Intermediate Java1 An example that uses inner classes Week Four Continued.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
OOP in Java – Inner Classes Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
CPSC150 JavaLynn Lambert CPSC150 Week 12 InheritanceInterfaces.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Interfaces & Polymorphism part 2:
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 Interfaces Reading for today: Sec and corresponding ProgramLive material. Also, compare with previous discussions of abstract classes (Sec. 4.7).
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
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.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Nested Classes CompSci 230 S Software Construction.
Generic Programming and Inner classes ge·ner·ic 1a : relating or applied to or descriptive of all members of a genus, species, class, or group : common.
Creating a GUI Class An example of class design using inheritance and interfaces.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Event Handling and Listeners in SWING The practice of event handling.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Object Oriented Programming in Java Habib Rostami Lecture 10.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
CSC 205 Programming II Lecture 7 AWT – Event Handling & Layout.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
CSC 205 Programming II Lecture 5 AWT - I.
Chapter 14 Event-Driven Programming
CHAPTER Reacting to the user.
A First Look at GUI Applications
Java Programming: From Problem Analysis to Program Design,
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Event-driven programming for GUI
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Chapter 16 Event-Driven Programming
A Quick Java Swing Tutorial
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
Presentation transcript:

1 Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes). A nested class is a static class that is defined inside another class. A nested class gets its own file drawer. A nested class can reference only static (and not non- static) variables of the class in which it is nested. public class X { public static final int Y= 2; private int x; private static class SC { private int p; private static int q; public void m() { p= Y; q= p; } } Reasons for using nested class. Get it out of the way (e.g. a once-used functor), perhaps make it private so others can’t refer to it directly. In method m, can reference, p, q, Y, but not x. A class that is not defined inside another can’t be static

2 Inner classes An inner class is a non-static class that is defined inside another class. We investigate such classes here. Start by defining a class that allows arrays of any size, like util.Vector (but simpler, to show the idea). // An array that changes to fit the required size public class DynamicArray { // Constructor: an array with 10 elements allocated public DynamicArray() {…} // = the number of elements in use public int length() {..} // = the element at index i (given 0 <= i < length()) public Object get(int i) {...} // set the element at position i to v (0 <= i) public void set(int i, Object v) {…} }

3 Class DynamicArray // An array that changes to fit the required size public class DynamicArray{ // b[0..n-1] are the elements. If n!=0, b[n-1] is the // element with highest index into which a value // was stored. private Object[] b; private int n; // Constructor: an array with 10 elements allocated public DynamicArray() { b= new Object[10]; n= 0; } // = the number of elements in use public int length() { return n; } // = the element at index i. // Precondition: 0 <= i < length() public Object get(int i) { return b[i]; }

4 Class DynamicArray (continued) // set the element at position i to v (0 <= i) public void set(int i, Object v) { if (i >= b.length) { // Create a new array newb with at least i+1 // elements. For efficiency, at least double the // array size Object[] newb= new Object[Math.max(i+1, 2*b.length)]; // Copy b[0..length()] into newb for (int j= 0; j != length(); j++) { newb[j]= b[j]; } b= newb; } // {i < b.length, so v can be stored in b[i]} b[i]= v; n= Math.max(n, i+1); }

5 An iterator over a DynamicArray import java.util.*; public class DAIterator implements Iterator { private DynamicArray b; // The array to process private int k= 0; // Next element to process. // 0 <= k <= b.length() // Constructor: an iterator over b public DAIterator(DynamicArray b) { this.b= b; } // = “there is another item to process” public boolean hasNext() { return k < b.length(); } // = the next item to process. Call only once per item // Throw an exception if no more items exist public Object next() { if (k == b.length()) throw new IllegalStateException("... "); k= k+1; return b.get(k-1); } // Not supported; does nothing public void remove() {} }

6 Problem with this iterator over DynamicArray Class DynamicArray and its iterator are separate, in two distinct files. Perhaps double what we need, and this makes a difference when there are hundreds of classes to maintain. Users don’t have to be able to see the iterator, they just have obtain a new instance when it is needed. Making the iterator an inner class is a better solution. An inner class is a non-static class that is defined inside another class.

7 DynamicArray with an inner class import java.util.*; public class DynamicArray{ private Object[] b; private int n; public DynamicArray() { … } public int length() { … } public Object get(int i) { … } public void set(int i, Object v) { … } // = an iterator over this DynamicArray public Iterator iterator() {return new DAIterator();} private class DAIterator implements Iterator { private int k= 0; public boolean hasNext() { return k < n; } public Object next() { if (k == n) throw new...(".. "); k= k+1; return b[k-1]; } public void remove() {} } inner class

8 DynamicArray with an inner class Important points about the previous slide. 1. Class DAIterator is a private component of class DynamicArray --private so that outsiders can’t see it. 2. Class DAIterator is in each instance of DynamicArray. 3. An instance of DAIterator has access to the fields of the instance of DynamicArray in which it was created -- see next slide. Because of this Array b can be referenced directly Variable n can be referenced directly 4. Field b of previous DAIterator is not needed. 5. Public method iterator to create an instance of DAIterator. 6. Inner classes cannot have static components.

9 The memory model and nested classes (remember, a nested class is static) An instance of a nested class has a scope box, which contains the name of class in which the nested class is defined. Reason: So methods in Y can access static variables of X. Suppose a0.m() is called (see below). Instance a1 is created, and its scope box is filled with name X. public class X { public static class Y {... } public Y m() {return new Y();} } a0 X a1 Y X scope box m

10 The memory model and inner classes (remember, an inner class is non-static) An instance of an inner class X (say) has a scope box. It contains the name Y (say) of the instance in which the inner class appears. Reason: So methods of X can reference fields of the instance of Y. Suppose a0.iterator() is called, where iterator is public Iterator iterator() { return new DAIterator(); } Instance a1 is created, and its scope box is filled with name a0 of the instance in which the iterator occurs. a0 DynamicArray b n lengthgetset iteratorDAIterator a1 DAIterator k hasNextnext removeDAIterator a0 scope box

11 Memory model: referencing a non-static name When looking for a non-static name: Look first in the frame. If not there, look (in bottom-up fashion) in the object x (say) given by the scope box of the frame. If not there, look (in bottom-up fashion) in the object y (say) given by x’s scope box. If not there, look (in bottom-up fashion) in the object given by y’s scope box. etc. a0 DynamicArray b n lengthgetset iteratorDAIterator a1 DAIterator k hasNextnext removeDAIterator a0 scope box nexta1 return address no pars or local vars frame for a call on next

12 Memory model: referencing a static name When looking for a static name in a frame for a call on a static method --the frame’s scope box is the name of a class C: Use the algorithm in the box below. mC return address pars and local vars frame for a call on static method m To find a static name given a class C: Look in class C’s file drawer. If not there, look in drawer for C’s superclass C1 (say). If not there, look in drawer for C1’s superclass C2 (say). … (continue in this fashion)...

13 Memory model: referencing a static name When looking for a static name in a frame for a call on a non-static method --the frame’s scope box is the name of an object a1 (say). An inner class cannot contain static declarations. Only inner-class objects have scope boxes. So execute this: Object t= a1; while (object t has a scope box) t= the name in t’s scope box; Now use the algorithm in the previous slide for finding a static name, using the class of object t a0 DynamicArray b n lengthgetset iteratorDAIterator a1 DAIterator k hasNextnext removeDAIterator a0 scope box nexta1 return address no pars or local vars frame for a call on next

14 An example: responding to a button press in a closeable window Reading: Weiss, sect. B.3.4. Event handling: adaptors... Develop a program that brings up this window on the monitor. Only one button is enabled. When the enabled button is pressed, it be- comes disabled and the other be- comes enabled. Use this to show a use of inner classes and anonymous classes. A window on the monitor corresponds to an instance of class JFrame. Get a window using JFrame jf= new JFrame(“title of frame”); jf.pack(); // Call after all components have been // added to window. jf.show(); // Make window visible on monitor Window jf has no button or other components. Clicking its close box hides the window but doesn’t terminate the program.

15 An example: making window closeable To have the program do something when close button is pressed, need to register a “window listener”, by (1) implementing class WindowListener (2) providing the seven methods of that class, each of which deals with one of the boxes in the title bar of the window or with the window as a whole. (3) Executing the following statement of method JFrame, addWindowListener(this); which registers the instance in which it appears as being a window listener, and (4) putting the following statement in the method that “listens” to a press of the close box: System.exit(0); See the next slide.

16 An example: making window closeable import javax.swing.*; import java.awt.event.*; public class CloseableFrame extends JFrame implements WindowListener { // Constructor: a Frame with good closebox, title t public CloseableFrame(String t) { super(t); addWindowListener(this); } // Terminate program. Called when closebox pressed public void windowClosing(WindowEvent e) { System.exit(0); } // Each of the following methods deals with one // of the window boxes or with some action on the // window. They don’t do anything public void windowClosed(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowOpened(WindowEvent e) {} }

17 An example: making window closeable The last slide was messy. To help out, Java provides an abstract class, like CloseableFrame, that contains empty methods for all seven methods. The class is called WindowAdapter. So we would like to do the following, but it’s illegal!! import javax.swing.*; import java.awt.event.*; public class CloseableFrame extends JFrame,WindowAdapter { // Constructor: a Frame with good closebox public CloseableFrame() { addWindowListener(this); } // Terminate program. Called when closebox pressed public void windowClosing(WindowEvent e) { System.exit(0); } } Can’t extend two classes

18 An example: making window closeable Solution to problem on previous slide: Provide an inner class, and let the inner class extend WindowAdapter. import javax.swing.*; import java.awt.event.*; public class CloseableFrame extends JFrame { // Constructor: a Frame with good closebox public CloseableFrame() { addWindowListener(new ExitOnClose()); } private class ExitOnClose extends WindowAdapter { // Terminate program when closebox pressed public void windowClosing(WindowEvent e) { System.exit(0); } } creation of instance of inner class

19 An example: making window closeable We can make the inner class anonymous: import javax.swing.*; import java.awt.event.*; public class CloseableFrame extends JFrame { // Constructor: a Frame with good closebox public CloseableFrame() { addWindowListener( new WindowAdapter() { // Terminate program when closebox pressed public void windowClosing(WindowEvent e) { System.exit(0); } } ); } anonymous class

20 An example: making window closeable After all this, we tell you that class JFrame provides a simpler solution. Simply call JFrame’s method setDefaultCloseOperation. JFrame jf= new JFrame(); jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); jf.pack(); jf.show(); But constant EXIT_ON_CLOSE is in class JFrame only since Java 2 version 1.3, not in version 1.2. Also, you can’t use this method when using the older class Frame So, what was said on previous slides is still useful.

21 Responding to a button press Develop a program that brings up this window on the monitor. Only one button is enabled. When the enabled button is pressed, it be- comes disabled and the other becomes enabled. Listening to a button requires implementing this interface --we need method ActionPerformed. A button press is one kind of “ActionEvent”. package java.awt.event; import java.util.EventListener; /** Implement this interface to have a class respond to ActionEvents for a Component. */ public interface ActionListener extends EventListener { /** Called when e happens in a Component with which this ActionListener is registered. Process a button press */ public void actionPerformed(ActionEvent e) { boolean b= (be.isEnabled()); be.setEnabled(!b); bw.setEnabled(b); }

22 An example: responding to a button press An instance of class JFrame is a window on your monitor. An instance of JButton is a Component that can be placed in a JFrame. Method main creates a new JFrame. We have to show what a constructor does and what actionPerformed does. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Applic extends JFrame implements ActionListener{ private JButton bw= new JButton("first"); private JButton be= new JButton("second"); public static void main(String pars[]) { Applic jF= new Applic("JFrame"); } // Constructor: a frame: two buttons, title t public Applic(String t) {... } public void actionPerformed(ActionEvent e) {... } };

23 An example: responding to a button press The constructor first calls the con- tructor of the superclass, giving it the title for the window. It then adds the two buttons to the window -- getContentPane is a JFrame method. It enables one button and disables the other. And it registers this in- stance as a “listener” for button presses. Then, it tells the JFrame to place all components. And its makes the window visible. Isn’t that easy? // Constructor: an Applic with two buttons and title t public Applic(String t) { super(t); getContentPane().add(bw, BorderLayout.WEST); getContentPane().add(be, BorderLayout.EAST); bw.setEnabled(false); be.setEnabled(true); // Set the actionlistener for the buttons bw.addActionListener(this); be.addActionListener(this); pack(); setVisible(true); }

24 An example: responding to a button press We can hide things by using an anonymous class. public class Applic extends JFrame { private JButton bw= new JButton("first"); private JButton be= new JButton("second"); // Constructor: an Applic with two buttons and title t public Applic(String t) {super(t); getContentPane().add(bw, BorderLayout.WEST); getContentPane().add(be, BorderLayout.EAST); bw.setEnabled(false); be.setEnabled(true); // Set the actionlistener for the buttons bw.addActionListener(al); be.addActionListener(al); pack(); setVisible(true); } private ActionListener al= new ActionListener() { // Process a button press public void actionPerformed(ActionEvent e) { boolean b= (be.isEnabled()); be.setEnabled(!b); bw.setEnabled(b); } }; }