Carnegie Mellon University, Graduate School of Industrial Administration 1 Event Handling Inner classes Event Handling and Inner Classes GUI Programming.

Slides:



Advertisements
Similar presentations
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Advertisements

Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann.
Summer A-2000, Project Course-- Carnegie Mellon University 1 Financial Engineering Project Course.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Event Handling Events and Listeners Timers and Animation.
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.
OOP Java1 Event Handling Overview Listeners, Adapters and Event Sources Inner classes Event Handling Details Applets and GUI Applications Event.
Carnegie Mellon University, MISM1 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann Thread.
OOP/Java1 Introductory Java Threads GUI examples taken from “Computing Concepts with Java 2” by Cay Horstmann Thread examples taken from “The Java.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
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,
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
Io package as Java’s basic I/O system continue’d.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
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 GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Event Driven Programming. Event-driven Programming In the early days of computing communication with the outside world was accomplished using a technique.
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.
UID – Event Handling and Listeners Boriana Koleva
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.
Object Oriented Programming.  Interface  Event Handling.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Event-Driven Programming 1.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Event-Driven Programming CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
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,
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
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.
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as event.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
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.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
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.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
GUIs and Events Rick Mercer.
CSC 205 Programming II Lecture 5 AWT - I.
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
CHAPTER Reacting to the user.
A First Look at GUI Applications
Ellen Walker Hiram College
GUI Event Handling Nithya Raman.
Event-driven programming for GUI
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Programming Graphical User Interface (GUI)
Presentation transcript:

Carnegie Mellon University, Graduate School of Industrial Administration 1 Event Handling Inner classes Event Handling and Inner Classes GUI Programming Threads and Web Servers Week Four

Carnegie Mellon University, Graduate School of Industrial Administration 2 Event Handling Used by the Abstract Window Toolkit (AWT) – for basic GUI programming Java 1.0 Used by Swing -- Better components than AWT Java 2 Used by JavaBeans -- reusable software components, like Visual Basic, that can be manipulated in a builder tool

Carnegie Mellon University, Graduate School of Industrial Administration 3 Babysitting A baby in the home needs attention. Many events surrounding the baby are not easily ignored. Events can be of different types.

Carnegie Mellon University, Graduate School of Industrial Administration 4 One possible source of events

Carnegie Mellon University, Graduate School of Industrial Administration 5 Babysitting Before responding to an event, a babysitter typically takes note of the source and the type of event.

Carnegie Mellon University, Graduate School of Industrial Administration 6 Babysitting The sitter needs to know both the event type and the event source. Event source Event type Handler

Carnegie Mellon University, Graduate School of Industrial Administration 7 Event Handling The window manager software may generate hundreds of different events. Examples include mouse clicks, mouse movements, key strokes, and timer ticks. A programmer is typically interested in a small subset of all of the possible events that may occur.

Carnegie Mellon University, Graduate School of Industrial Administration 8 Events and Event Objects Since events may be of different types but still exhibit some shared traits (inheritance) Java represents the event classes in a hierarchy. The root class is called java.util.EventObject. The only common feature shared by all events is a source object. So we find the following method in the EventObject class : public Object getSource();

Carnegie Mellon University, Graduate School of Industrial Administration 9 EventObject AWTEvent ActionEventComponentEvent InputEvent WindowEvent MouseEvent KeyEvent Some classes and methods in the event hierarchy. Object String getActionCommand() int getX() char getKeyChar() boolean isAltDown()Window getWindow()

Carnegie Mellon University, Graduate School of Industrial Administration 10 Event handling usually involves three types of objects Objects are used to hold and report on information about the event. Objects are typically the source of events. Objects, called listeners, are used to handle events.

Carnegie Mellon University, Graduate School of Industrial Administration 11 Example A mouse object A mouse object An event object that describes, say, the x and y coordinate of where the mouse was clicked The listener object has methods that are called for particular events Event Source Event data and methods Listener

Carnegie Mellon University, Graduate School of Industrial Administration 12 Example A mouse object A mouse object An event object that describes, say, the x and y coordinate of where the mouse was clicked The listener object has methods that are called for particular events Implements MouseListener The event object is sent to a listener method A mouse object must be told who its listener is.

Carnegie Mellon University, Graduate School of Industrial Administration 13 The Listener There are different types of Listeners. MouseListeners WindowListeners ScrollBarListeners Etc.. These Listeners are interfaces. Remember what an interface provides? If class X implements an interface then class X promises to provide (at least) the methods declared in the interface.

Carnegie Mellon University, Graduate School of Industrial Administration 14 Some of the Listener Hierarchy EventListener ActionListener abstract void actionPerformed(ActionEvent e); MouseListener abstract void mouseClicked(MouseEvent e) KeyListener

Carnegie Mellon University, Graduate School of Industrial Administration 15 A Listener Interface public interface MouseListener { void mouseClicked(MouseEvent e); void mouseEntered(MouseEvent e); void mouseExited(MouseEvent e); void mouseReleased(MouseEvent e); } //What does it mean if I claim that I implement this interface?

Carnegie Mellon University, Graduate School of Industrial Administration 16 An Example // MouseSpyApplet.java import java.applet.Applet; import java.awt.event.MouseEvent; import java.awt.event.MouseListener;

Carnegie Mellon University, Graduate School of Industrial Administration 17 class MouseSpy implements MouseListener { public void mouseClicked(MouseEvent event) { System.out.println("Mouse clicked. x = " + event.getX() + " y = " + event.getY()); } public void mouseEntered(MouseEvent event) { System.out.println("Mouse entered. x = " + event.getX() + " y = " + event.getY()); } public void mouseExited(MouseEvent event) { System.out.println("Mouse exited. x = " + event.getX() + " y = " + event.getY()); } public void mousePressed(MouseEvent event) { System.out.println("Mouse pressed. x = " + event.getX() + " y = " + event.getY()); } public void mouseReleased(MouseEvent event) { System.out.println("Mouse released. x = " + event.getX() + " y = " + event.getY()); } I have to provide ALL of these methods!!

Carnegie Mellon University, Graduate School of Industrial Administration 18 public class MouseSpyApplet extends Applet { public MouseSpyApplet() { MouseSpy listener = new MouseSpy(); addMouseListener(listener); }

Carnegie Mellon University, Graduate School of Industrial Administration 19 Spying on the mouse Java Applets need an HTML file.

Carnegie Mellon University, Graduate School of Industrial Administration 20 Another approach Suppose a friendly sole created this class: public class MouseAdapter implements MouseListener { void mouseClicked(MouseEvent e){} void mouseEntered(MouseEvent e){} void mouseExited(MouseEvent e){} void mouseReleased(MouseEvent e){} } Now, suppose I extend this class. What must I provide?

Carnegie Mellon University, Graduate School of Industrial Administration 21 Only those methods that I am interested in. The other methods, when called, do nothing. We’ll visit this issue again later.

Carnegie Mellon University, Graduate School of Industrial Administration 22 Inner Classes Nested Top Level Classes (not inner) Member Classes Local Classes Anonymous Classes

Carnegie Mellon University, Graduate School of Industrial Administration 23 Nested Top Level Class Nested top-level classes are not inner classes. Use as a convenient way to group related classes Since the class must be static and has no 'this' pointer, it has no access to the instance data of objects for its enclosing class. It behaves just like a 'normal' class or interface.

Carnegie Mellon University, Graduate School of Industrial Administration 24 //NestedTopLevelExample.java class Top { int i,j; static class SomeClass { // static makes it top-level nested int k; SomeClass() { System.out.println("Constructing SomeClass"); } void foo() { System.out.println("Hello"); } } Top() { System.out.println("Constructing a Top object"); }

Carnegie Mellon University, Graduate School of Industrial Administration 25 public class NestedTopLevelExample { public static void main(String args[]) { Top myTop = new Top(); Top.SomeClass myObject = new Top.SomeClass(); myObject.foo(); } Output Constructing a Top object Constructing SomeClass Hello

Carnegie Mellon University, Graduate School of Industrial Administration 26 Member Classes Member classes (there is no such thing as a 'member‘ interface) This inner class (it's not a top-level class) has no static keyword and can access the members of each object of its outer class. The class 'appears in every instance'.

Carnegie Mellon University, Graduate School of Industrial Administration 27 The parent class must declare an instance of an inner class, before it can invoke the inner class methods, assign to data fields (including private ones), and so on. Unlike nested top-level classes, inner classes are not directly part of a package and are not visible outside the class in which they are nested. Inner classes are often used for GUI event handlers.

Carnegie Mellon University, Graduate School of Industrial Administration 28 // MemberClassExample.java class Top { int i = 33; public class SomeClass { // access the outer object's state. private int k = i; SomeClass() { System.out.println("Constructing SomeClass"); } void foo() { System.out.println("Hello"); } } Top() { System.out.println("Constructing a Top object"); SomeClass sc = new SomeClass(); System.out.println(sc.k); }

Carnegie Mellon University, Graduate School of Industrial Administration 29 public class MemberClassExample { public static void main(String args[]) { Top myObject = new Top(); } // OUTPUT Constructing a Top object Constructing SomeClass 33

Carnegie Mellon University, Graduate School of Industrial Administration 30 Local Classes A Local class is an inner class. Typically, a local class is declared within a method. It is not a member of an enclosing class. It is visible only within the block. These classes are used primarily as "adapter classes". For example, a block of code that creates a Button object could use a local class to define a simple implementation of the ActionListener Interface. Then it could instantiate this simple implementation and pass the resulting object to the button's ActionListener method, thereby connecting the button to the "callback" code that is executed when the button is pressed.

Carnegie Mellon University, Graduate School of Industrial Administration 31 // Local Class example class Top { int i = 33; Top() { System.out.println("Constructing a Top object"); // define a class within a method class Wow { int t; Wow() { System.out.println("Building a Wow"); i = 8; t = 9; } Wow h = new Wow(); System.out.println(" h.t == " + h.t); System.out.println(" i == " + i); }

Carnegie Mellon University, Graduate School of Industrial Administration 32 public class LocalExample { public static void main(String args[]) { Top myObject = new Top(); } // OUTPUT Constructing a Top object Building a Wow h.t == 9 i == 8

Carnegie Mellon University, Graduate School of Industrial Administration 33 An anonymous class is refinement of inner classes. It allows you to combine the definition of the class with the instance allocation. Since it is instantiated in the same expression that defines it, it can only be instantiated once. This is very similar to local classes. When writing a simple adapter class, the choice between a named local class and an unnamed anonymous class typically comes down to a matter of style and code clarity, rather than any difference in functionality. The new class can't have a constructor. Anonymous Classes

Carnegie Mellon University, Graduate School of Industrial Administration 34 // Anonymous.java interface SmallClass { public void foo(); } class Top { int i = 33; void someMethod(SmallClass s) { s.foo(); } void anotherMethod() { someMethod(new SmallClass() { public void foo() { System.out.println("Really fun"); } }); }

Carnegie Mellon University, Graduate School of Industrial Administration 35 Top() { System.out.println("Constructing a Top object"); someMethod(new SmallClass() { public void foo() { System.out.println("Strange but fun"); } }); }

Carnegie Mellon University, Graduate School of Industrial Administration 36 public class Anonymous { public static void main(String args[]) { // We can't create interface objects // error: SmallClass s = new SmallClass(); Top myObject = new Top(); myObject.anotherMethod(); } // OUTPUT Constructing a Top object Strange but fun Really fun

Carnegie Mellon University, Graduate School of Industrial Administration 37 Event Handling and Inner Classes register Source ObjectListener Object fire events After the listener object registers itself with the source object, the source object calls a method found in the listener object and passes an object that describes the event. Event object

Carnegie Mellon University, Graduate School of Industrial Administration 38 Event Handling Suppose we have a Button object Button b = new Button(); We must determine what events a particular component generates. A Button component may generate an ActionEvent object. Button b ActionEvent Object ActionEvent Object

Carnegie Mellon University, Graduate School of Industrial Administration 39 Implementing a Listener class BabySitter implements ActionListener { public void actionPerformed(ActionEvent e) { // handle the event object e in some way } We need an object that will listen for the ActionEvent. We implement the ActionListener class (this class listens for ActionEvents from buttons, menus, etc.) and override its actionPerformed method.

Carnegie Mellon University, Graduate School of Industrial Administration 40 Create a BabySitter object BabySitter sitter = new BabySitter(); sitter

Carnegie Mellon University, Graduate School of Industrial Administration 41 Registering The Listener We want to listen for the ActionEvent object coming from the button. So, we tell the button what object will listen for the ActionEvent object: b.addActionListener(sitter)

Carnegie Mellon University, Graduate School of Industrial Administration 42 The button and its listener Button Object Sitter Object The button calls the actionPerformed() method of the sitter object and passes an ActionEvent object as a parameter addActionListener

Carnegie Mellon University, Graduate School of Industrial Administration 43 Hit the X and the program exits Once again but with a window

Carnegie Mellon University, Graduate School of Industrial Administration 44 Create a WindowCloseSitter Class import javax.swing.*; import java.awt.event.*; public class CloseDemo { public static void main(String[] args) { JFrame f = new JFrame("Example"); f.setSize(400,100); f.setVisible(true); WindowCloseSitter h = new WindowCloseSitter(); f.addWindowListener(h); }

Carnegie Mellon University, Graduate School of Industrial Administration 45 class WindowCloseSitter implements WindowListener { public void windowClosing(WindowEvent e) { System.exit(0); } public void windowClosed(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } } But we have to implement ALL of the functions !!

Carnegie Mellon University, Graduate School of Industrial Administration 46 Java Provides Adapter Classes ComponentAdapter MouseMotionAdapter WidowAdapter ContainerAdapter MouseAdapter FocusAdapter KeyAdapter

Carnegie Mellon University, Graduate School of Industrial Administration 47 The WindowAdapter class public abstract class WindowAdapter implements WindowListener { public void windowClosing(WindowEvent e) {} public void windowClosed(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } } A built in class -- we already have the empty bodies!!

Carnegie Mellon University, Graduate School of Industrial Administration 48 The Window again import javax.swing.*; import java.awt.event.*; public class CloseDemo2 extends WindowAdapter { public static void main(String[] args) { JFrame f = new JFrame("Example"); f.setSize(400,100); f.setVisible(true); f.addWindowListener(new CloseDemo2()); } public void windowClosing(WindowEvent e) { System.exit(0); }

Carnegie Mellon University, Graduate School of Industrial Administration 49 Again with anonymous classes import javax.swing.*; import java.awt.event.*; public class CloseDemo3 { public static void main(String[] args) { JFrame f = new JFrame("Example"); f.setSize(400,100); f.setVisible(true); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } ); } }

Carnegie Mellon University, Graduate School of Industrial Administration 50 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann Thread examples taken from “The Java Programming Language” By Arnold and Gosling and from Cay Horstmann’s “Core Java 2 Advanced” GUI Programming with threads

Carnegie Mellon University, Graduate School of Industrial Administration 51 Frame Windows A Frame window has a border and a title bar A Frame window has an addWindowListener method. We can use this method to add listeners to our frame window.

Carnegie Mellon University, Graduate School of Industrial Administration 52 An example import javax.swing.*; import java.awt.event.*; public class InternetFrameExample { public static void main(String[] args) { JFrame f = new InternetFrame("Example"); f.setTitle("Internet browser"); f.show(); } javax means Java standard extension Tell the window manager to display the frame.

Carnegie Mellon University, Graduate School of Industrial Administration 53 class InternetFrame extends JFrame { public InternetFrame(String s){ setSize(300,300); WindowCloser listener = new WindowCloser(); addWindowListener(listener); } private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } windowOpened() widowClosed() windowClosing() : Add the handler

Carnegie Mellon University, Graduate School of Industrial Administration 54

Carnegie Mellon University, Graduate School of Industrial Administration 55 Adding User Interface Components to a Frame Do not draw directly on the surface of a frame. Frames have been designed to arrange user interface components. User interface components are such things as buttons, menus, scroll bars, and so on. If you want to draw on a frame, draw on a separate component and then add that component to the frame. The Swing UI toolkit provides the Jpanel class for this purpose.

Carnegie Mellon University, Graduate School of Industrial Administration 56 Drawing on a JPanel To draw on a Jpanel you override the paintComponent method. Make sure that from within your paintComponent method you call super.paintComponent(…) so that the superclass method paintComponent has a chance to erase the existing contents, redraw the borders and decorations, etc.

Carnegie Mellon University, Graduate School of Industrial Administration 57 Adding the Panel to the JFrame The surface of a Swing frame is covered with four panes. Each of these four has a purpose. We are interested in getting access to the JFrame’s content pane. So, call the getContentPane on the JFrame. This call returns a Container object. Add your Panel object to the content pane Container.

Carnegie Mellon University, Graduate School of Industrial Administration 58 Adding a Panel to a JFrame x = getContentPane (a contentPane holds components for display). x refers to a Container (may contain other components) c = a Panel or some other component. Add c to x using x’s layout manager (a content pane uses border layout) JFrame getContentPane()

Carnegie Mellon University, Graduate School of Industrial Administration 59 Adding a JTextfield to the JFrame JFrame getContentPane() class MyFrame extends JFRAME { private JTextField textField; public MyFrame() { Container cp = getContentPane(); textField = new JTextField(); cp.add(textField, “South”); cp

Carnegie Mellon University, Graduate School of Industrial Administration 60 We may want to add a listener to the TextField JFrame getContentPane() Class MyFrame extends JFRAME { private JTextField textField; public myFrame() { Container cp = getContentPane(); textField = new JTextField(); cp.add(textField, “South”); textField.addActionListener( new TextFieldListener()); cp

Carnegie Mellon University, Graduate School of Industrial Administration 61 Output first! -- user enters number of eggs and we draw them

Carnegie Mellon University, Graduate School of Industrial Administration 62 Strategy Think about What do we want on the screen? What events should we listen for? What should we do when those events occur? What processing will we do when user input arrives? What object has responsibilities for what activities? Think about The ‘has-a’ relationship,e.g., the Jframe’s ContentPane “has-a” Panel and a TextField. The ‘is-a’ relationship,e.g., The TextFieldListener ‘is-an’ actionListener.

Carnegie Mellon University, Graduate School of Industrial Administration 63 // Example // Eggs.java import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Ellipse2D; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; We need classes from the awt, util, and swing packages.

Carnegie Mellon University, Graduate School of Industrial Administration 64 public class Eggs { public static void main(String[] args) { EggFrame frame = new EggFrame(); frame.setTitle("Enter number of eggs"); frame.show(); } This thread is done after creating a frame and starting up the frame thread. A frame now exists and is running.

Carnegie Mellon University, Graduate School of Industrial Administration 65 The EggFrame Constructor Set the size of the frame Add a listener to listen for the stop event Create a JPanel object to draw on and a JTextField object to interact with the user via the keyboard Add a listener for the JTextField Add the Jpanel and the JTextField to the contentPane container.

Carnegie Mellon University, Graduate School of Industrial Administration 66 class EggFrame extends JFrame { private JTextField textField; private EggPanel panel; public EggFrame() { final int DEFAULT_FRAME_WIDTH = 300; final int DEFAULT_FRAME_HEIGHT = 300; setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT); addWindowListener(new WindowCloser()); panel = new EggPanel(); textField = new JTextField(); textField.addActionListener(new TextFieldListener()); Container contentPane = getContentPane(); contentPane.add(panel, "Center"); contentPane.add(textField, "South"); } A listener for the jframe window A textField listener As before

Carnegie Mellon University, Graduate School of Industrial Administration 67 The constructor will be called from our main thread. The other thread operates asynchronously. What do we mean by asynchronous execution? Who is running the show? Don’t programs run sequentially? We have to think differently. Event driven programming

Carnegie Mellon University, Graduate School of Industrial Administration 68 The TextField The TextField object will call us when it detects an event. We don’t ‘read the input’. We set up a babysitter to respond. The TextField object sends us an event object.

Carnegie Mellon University, Graduate School of Industrial Administration 69 // Use an inner class to listen on the text field private class TextFieldListener implements ActionListener { public void actionPerformed(ActionEvent event) { String input = textField.getText(); panel.setEggCount(Integer.parseInt(input)); textField.setText(""); } We do two things when we have a textfield event. 1)Get the data 2)Tell the panel the number of eggs to display

Carnegie Mellon University, Graduate School of Industrial Administration 70 // Use an inner class to listen on the text field private class TextFieldListener implements ActionListener { public void actionPerformed(ActionEvent event) { String input = textField.getText(); panel.setEggCount(Integer.parseInt(input)); textField.setText(""); } Note how handy the inner class is. Both panel and textField are available. What if the listener were not an object of an inner class. how would it get access to these variables? We can’t just pass the variables on the call because we don’t make the call.

Carnegie Mellon University, Graduate School of Industrial Administration 71 private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } This is how we respond when the close signal is received. system.exit(0) stops the java virtual machine. 0 means normal termination.

Carnegie Mellon University, Graduate School of Industrial Administration 72 How about the panel object What are the panel object’s responsibilities? get input? _____ repaint itself? _____ keep track of the egg count? _____ hold the data it needs to repaint itself? _____ Do we want our panel to inherit properties and methods from any existing classes? _____

Carnegie Mellon University, Graduate School of Industrial Administration 73 How about the panel object What are the panel object’s responsibilities? get input? No, that’s the TextField’s job. repaint itself? Sure, that’s its main job. keep track of the egg count? Yes, better here where it’s needed hold the data it needs to repaint itself? Yes Do we want our panel to inherit properties from any existing classes? Sure, we want to re-use existing code whenever possible.

Carnegie Mellon University, Graduate School of Industrial Administration 74 How about the panel object When should the panel object repaint itself? What will the panel need to repaint itself? Who actually calls the paintComponent method?

Carnegie Mellon University, Graduate School of Industrial Administration 75 How about the panel object When should the panel object repaint itself? When a new input arrives from the user. When the egg count changes. What will the panel need to repaint itself? A graphics objectto draw on. Who actually calls the paintComponent method? While we have to provide a paintComponent method we don’t call it directly. It’s called by the Java run-time environment after we make a call on repaint.

Carnegie Mellon University, Graduate School of Industrial Administration 76 class EggPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; // draw eggCount ellipses with random centers Random generator = new Random(); for (int i = 0; i < eggCount; i++) { double x = getWidth() * generator.nextDouble(); double y = getHeight() * generator.nextDouble(); Ellipse2D.Double egg = new Ellipse2D.Double(x, y, EGG_WIDTH, EGG_HEIGHT); g2.draw(egg); }

Carnegie Mellon University, Graduate School of Industrial Administration 77 public void setEggCount(int count) { eggCount = count; repaint(); } private int eggCount; private static final double EGG_WIDTH = 30; private static final double EGG_HEIGHT = 50; }

Carnegie Mellon University, Graduate School of Industrial Administration 78 Java Threads Four kinds of thread programming Applications –A GUI application –A server application

Carnegie Mellon University, Graduate School of Industrial Administration 79 Four kinds of thread programming 1) Unrelated threads 2) Related but unsynchronized threads 3) Mutually-exclusive threads 4) Communicating mutually-exclusive threads We will look at only the first two kinds.

Carnegie Mellon University, Graduate School of Industrial Administration 80 class Coffee extends Thread { Coffee(String name) { super(name); } public void run() { for(int n = 1; n <= 3; n++) { System.out.println("I like coffee"); yield(); System.out.println(this.getName()); yield(); } Unrelated threads

Carnegie Mellon University, Graduate School of Industrial Administration 81 class Tea extends Thread { Tea(String name) { super(name); } public void run() { for(int n = 1; n <= 3; n++) { System.out.println("I like tea"); yield(); System.out.println(this.getName()); yield(); }

Carnegie Mellon University, Graduate School of Industrial Administration 82 public class Drinks { public static void main(String args[]) { System.out.println("I am main"); Coffee t1 = new Coffee("Wawa Coffee"); Tea t2 = new Tea(“Sleepy Time Tea"); t1.start(); t2.start(); System.out.println("Main is done"); }

Carnegie Mellon University, Graduate School of Industrial Administration 83 I am main Main is done I like coffee I like tea Wawa Coffee Sleepy Time Tea I like coffee I like tea Wawa Coffee Sleepy Time Tea I like coffee I like tea Wawa Coffee Sleepy Time Tea Output Main finishes right away Threads are sharing time This program has three threads.

Carnegie Mellon University, Graduate School of Industrial Administration 84 Using sleep() in unrelated threads The call sleep(millis) puts the currently executing thread to sleep for at least the specified number of milliseconds. "At least“ means there is no guarantee the thread will wake up in exactly the specified time. Other thread scheduling can interfere. Unrelated Threads Part II

Carnegie Mellon University, Graduate School of Industrial Administration 85 class Coffee extends Thread { Coffee(String name) { super(name); } public void run() { for(int n = 1; n <= 3; n++) { System.out.println("I like coffee"); try { sleep(1000); // 1 second } catch(InterruptedException e) {} System.out.println(this.getName()); }

Carnegie Mellon University, Graduate School of Industrial Administration 86 class Tea extends Thread { Tea(String name) { super(name); } public void run() { for(int n = 1; n <= 5; n++) { System.out.println("I like tea"); System.out.println(getName()); }

Carnegie Mellon University, Graduate School of Industrial Administration 87 public class Drinks2 { public static void main(String args[]) { System.out.println("I am main"); Coffee t1 = new Coffee("Wawa Coffee"); Tea t2 = new Tea("China Tea"); t1.start(); t2.start(); System.out.println("Main is done"); }

Carnegie Mellon University, Graduate School of Industrial Administration 88 I am main Main is done I like coffee I like tea China Tea I like tea China Tea I like tea China Tea I like tea China Tea I like tea China Tea Wawa Coffee I like coffee Wawa Coffee I like coffee Wawa Coffee 1 second pausing after each “I like coffee” After “I like coffee”, the coffee thread goes to sleep and the tea thread gets to finish and die.

Carnegie Mellon University, Graduate School of Industrial Administration 89 Yield() and Sleep() Yield() may have no effect on some implementations. The thread scheduler might make no effort toward fairness. The yielding thread may be picked again even though other threads want a turn. It is a good idea to call sleep() instead.

Carnegie Mellon University, Graduate School of Industrial Administration 90 An Example Without Threads Black ball bounces for awhile and then stops. If you then click start, a new ball bounces for awhile and then stops. Close only works between balls. If the ball is moving and you click close, the close message is queued.

Carnegie Mellon University, Graduate School of Industrial Administration 91 // From Cay Horstmann Core Java 2 Advanced import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Bounce { public static void main(String[] args) { JFrame frame = new BounceFrame(); frame.show(); }

Carnegie Mellon University, Graduate School of Industrial Administration 92 class BounceFrame extends JFrame { public BounceFrame() { setSize(300, 200); setTitle("Bounce"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } );

Carnegie Mellon University, Graduate School of Industrial Administration 93 Container contentPane = getContentPane(); canvas = new JPanel(); contentPane.add(canvas, "Center"); JPanel p = new JPanel(); addButton(p, "Start", new ActionListener() { public void actionPerformed(ActionEvent evt) { Ball b = new Ball(canvas); b.bounce(); } });

Carnegie Mellon University, Graduate School of Industrial Administration 94 addButton(p, "Close", new ActionListener() { public void actionPerformed(ActionEvent evt) { System.exit(0); } }); contentPane.add(p, "South"); } public void addButton(Container c, String title, ActionListener a) { JButton b = new JButton(title); c.add(b); b.addActionListener(a); } private JPanel canvas; }

Carnegie Mellon University, Graduate School of Industrial Administration 95 class Ball { public Ball(JPanel b) { box = b; } public void draw() { Graphics g = box.getGraphics(); g.fillOval(x, y, XSIZE, YSIZE); g.dispose(); }

Carnegie Mellon University, Graduate School of Industrial Administration 96 public void move() { Graphics g = box.getGraphics(); g.setXORMode(box.getBackground()); g.fillOval(x, y, XSIZE, YSIZE); x += dx; y += dy; Dimension d = box.getSize(); if (x < 0) { x = 0; dx = -dx; } if (x + XSIZE >= d.width) { x = d.width - XSIZE; dx = -dx; } if (y < 0) { y = 0; dy = -dy; } if (y + YSIZE >= d.height) { y = d.height - YSIZE; dy = -dy; } g.fillOval(x, y, XSIZE, YSIZE); g.dispose(); }

Carnegie Mellon University, Graduate School of Industrial Administration 97 public void bounce() { draw(); for (int i = 1; i <= 1000; i++) { move(); try { Thread.sleep(5); } catch(InterruptedException e) {} } private JPanel box; private static final int XSIZE = 10; private static final int YSIZE = 10; private int x = 0; private int y = 0; private int dx = 2; private int dy = 2; }

Carnegie Mellon University, Graduate School of Industrial Administration 98 Bouncing With Threads The close button works in an instant. Each time the start button is clicked a new ball appears. The screen above shows four fast moving bouncing balls.

Carnegie Mellon University, Graduate School of Industrial Administration 99 addButton(p, "Start", new ActionListener() { public void actionPerformed(ActionEvent evt) { Ball b = new Ball(canvas); b.start(); } }); We use start() rather than bounce() on the ball object…

Carnegie Mellon University, Graduate School of Industrial Administration 100 …and have the Ball class extend Thread and implement run() rather than bounce(). class Ball extends Thread : public void run() { try { draw(); for (int i = 1; i <= 1000; i++) { move(); sleep(5); } catch(InterruptedException e) {} }

Carnegie Mellon University, Graduate School of Industrial Administration 101 Ping Pong Adapted from "The Java Programming Language", Arnold and Gosling After a thread is created, you can configure it – set its name, its initial priority, and so on. The start() method spawns a new thread of control based on the data in the thread object and then returns. Now, the Java virtual machine invokes the new thread's run method, making the thread active. When a thread's run method returns, the thread has exited. The thread may be manipulated with a number of methods, including the interrupt() method as shown in this example.

Carnegie Mellon University, Graduate School of Industrial Administration 102 public class PingPong extends Thread { private String word; private int delay; public PingPong(String whatToSay, int delayTime) { word = whatToSay; delay = delayTime; }

Carnegie Mellon University, Graduate School of Industrial Administration 103 public void run() { try { for(;;) { System.out.println(word+" "); sleep(delay); } catch (InterruptedException e) { System.out.println("Interrupted!!!!!"); return; }

Carnegie Mellon University, Graduate School of Industrial Administration 104 public static void main(String args[]) { PingPong t1 = new PingPong("\tping",33); t1.start(); PingPong t2 = new PingPong("Pong",100); t2.start(); try { Thread.sleep(5000); } catch(InterruptedException e) { // will not be printed System.out.println("Good morning"); return; }

Carnegie Mellon University, Graduate School of Industrial Administration 105 Thread myThread = Thread.currentThread(); for (int t = 1 ; t <= 10; t++) System.out.println("In Main..." + myThread.getName()); t1.interrupt(); }

Carnegie Mellon University, Graduate School of Industrial Administration 106 C:\McCarthy\threads\PingPong>java PingPong ping Pong ping Pong ping Pong ping : Main is asleep. For 5 seconds ping and pong take turns sleeping and running

Carnegie Mellon University, Graduate School of Industrial Administration 107 Pong ping Pong In Main...main Interrupted!!!!! Pong : “Pongs” forever or until until ctrl-c Main wakes up Main interrupts Ping and ping dies.

Carnegie Mellon University, Graduate School of Industrial Administration 108 A Thread Application --A Simple Web Server Responds by sending the same file on each hit Creates a new thread on each hit

Carnegie Mellon University, Graduate School of Industrial Administration 109 // A simple web server // Responds with the same file on each hit import java.net.*; import java.io.*; import java.util.*; public class OneFile extends Thread { static String theData = ""; static String contentType; static int contentLength; Socket theConnection;

Carnegie Mellon University, Graduate School of Industrial Administration 110 // construct each OneFile object with an existing socket public OneFile(Socket s) { theConnection = s; } // run the following code on each object public void run() { try { // get a PrintStream attached to this socket PrintStream os = new PrintStream( theConnection.getOutputStream()); // get a DataInputStream attached to this socket DataInputStream is = new DataInputStream( theConnection.getInputStream()); // read a line from the socket String request = is.readLine();

Carnegie Mellon University, Graduate School of Industrial Administration 111 // HTTP/1.0 and later send a MIME header if(request.indexOf("HTTP/") != -1) { // we need to read the rest of the MIME header while(true) { String thisLine = is.readLine(); if(thisLine.trim().equals("")) break; } // respond to the client os.print("HTTP/ OK\r\n"); // send the date Date now = new Date(); os.print("Date: " + now + "\r\n"); // send our name os.print("Server: OneFile 1.0\r\n");

Carnegie Mellon University, Graduate School of Industrial Administration 112 // send the contentLength os.print("Content-length: " + contentLength + "\r\n"); // send the content type os.print("Content-type: " + contentType + "\r\n\r\n"); } // send the file in the string os.println(theData); theConnection.close(); } catch(IOException e) { }

Carnegie Mellon University, Graduate School of Industrial Administration 113 // main loads the file and creates the object on every hit public static void main(String args[] ) { int thePort; ServerSocket ss; Socket theConnection; FileInputStream theFile; // cache the file try { // open file and create a DataInputStream theFile = new FileInputStream(args[0]); DataInputStream dis = new DataInputStream(theFile);

Carnegie Mellon University, Graduate School of Industrial Administration 114 // determine the content type of this file if(args[0].endsWith(".html") || args[0].endsWith(".htm") ) { contentType = "text/html"; } else { contentType = "text/plain"; } // read the file into the string theData try { String thisLine; while((thisLine = dis.readLine()) != null) { theData += thisLine + "\n"; } catch(Exception e) { System.err.println("Error " + e); }

Carnegie Mellon University, Graduate School of Industrial Administration 115 catch(Exception e) { System.err.println(e); System.err.println("usage: java onefile filename port"); System.exit(1); } // set the port to listen on try { thePort = Integer.parseInt(args[1]); if(thePort 65535) thePort = 80; } catch(Exception e) { thePort = 80; }

Carnegie Mellon University, Graduate School of Industrial Administration 116 // create a server socket try { ss = new ServerSocket(thePort); System.out.println("Accepting connections on port " + ss.getLocalPort()); System.out.println("Data to be sent:"); System.out.println(theData); while(true) { // stop and wait for a connection Socket socketTemp = ss.accept(); // we have a socket so create a handler OneFile fs = new OneFile(socketTemp); // start the handler running fs.start(); } catch(IOException e) {System.out.println("Socket error"); } }