University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Inheritance III, Graphical User Interfaces Lecture.

Slides:



Advertisements
Similar presentations
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Advertisements

1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Inheritance II Lecture 23, Thu Mar
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Graphical User Interfaces Lecture 25, Thu Apr
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Interfaces, Polymorphism II Lecture 21, Thu Mar
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Advanced Class Design Lecture 19, Thu Mar
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Graphics Programming. In this class, we will cover: The difference between AWT and Swing Creating a frame Frame positioning Displaying information in.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design Lecture 30, Mon Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Interfaces, Polymorphism Lecture 29, Fri Mar
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Arrays and Class Design Lecture 18, Tue Mar
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Yet More Array Practice Lecture 24, Mon Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design III, Parameter/Scope Review Lecture.
Java Concepts Chapter 2 – Graphical Applications Mr. Smith AP Computer Science A.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
A.k.a. GUI’s.  If you want to discuss your Lab 2 grade come see me this week. ◦ Office: 436 ERB. One hour prior to class ◦ Open to Appointments MWF 
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Learn about the types of Graphics that are available Develop a basic Graphics applet Develop a basic Graphics application Review the Java API and use.
Lecture 5: Interaction 1  Principles of Interactive Graphics  CMSCD2012  Dr David England, Room 711,  ex 2271 
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
Lab 6: Shapes & Picture Extended Ellipse & Rectangle Classes Stand-Alone GUI Applications.
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,
Chapter 12 Event Handling. Chapter Goals To understand the Java event model To install action and mouse event listeners To accept input from buttons,
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 13 : Swing I King Fahd University of Petroleum & Minerals College of Computer Science.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
1 Block1 – unit 2 (The Case study in Budd 5-6).  create a small application that uses the Abstract Windowing Toolkit (AWT)  Swing packages to simulate.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. In order to display a drawing in a frame, define a class that extends.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Fall 2006Adapded from Java Concepts Companion Slides1 Event Handling Advanced Programming ICOM 4015 Lecture 13 Reading: Java Concepts Chapter 12.
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.
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
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.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Graphical User Interfaces Lecture 24, Tue Apr
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming – Home and reload buttons for the webbrowser, Applets.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
Graphical User Interface (GUI) Two-Dimensional Graphical Shapes.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
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.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Lecture 15 Basic GUI programming
CSC 205 Programming II Lecture 5 AWT - I.
A First Look at GUI Applications
Java Programming: From Problem Analysis to Program Design,
Ellen Walker Hiram College
Inheritance, Polymorphism, and Interfaces
Chapter 12 Event Handling
Week 6 Object-Oriented Programming (2): Polymorphism
Presentation transcript:

University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Inheritance III, Graphical User Interfaces Lecture 35, Wed Apr borrowing from slides by Kurt Eiselt

2 Office Hours n reminder: TA office hours at DLC end Thu afternoon n labs end this week n my office hours for rest of term n Monday 4/19 4pm n by appointment through 4/23 n send me to book n not Mon 4/26 n I'm out of town 4/24-4/27 n will check at least once/day, but not online all the time

3 Assignments n Assignment 3 due Fri Apr 16, 5pm n electronic handin only n writeup hardcopy handed out mentioned hardcopy, ignore that! (fixed in online version) n Assignment 2 grading reports should arrive by very soon n ugrad account check it or forward it to your real account n A3 grading report target is Apr 26, so you have a few days to look through before final

4 Midterm n deadline for having TAs check corrected midterms is the Thu lab tomorrow n then solutions released n Vista currently has unscaled, difference mark as Assignment 2 Correction n after it's finalized, we'll add two more columns n scaled difference n scaled combined

5 Weekly Questions n you'll get full credit if you handed in questions for 10 (out of the 12 possible) weeks n last one due today n reminder: weeklies all together count for 2% of your course grade

6 Final Exam n final review session will be Mon Apr 24 n 10am-12pm, room WOOD 4 n given by grad TA Primal Wijesekera n final is Wed Apr 28, 3:30-6:30 pm, FSC 1005 n exam will be 2.5 hours n 3 hour slot reserved in case of fire alarms, etc n closed book/notes/laptops/calculators n material covered n whole course, but significant emphasis on later topics not covered in previous exams n exception: GUIs will not be covered

7 Material Covered n midterm 1 n primitives, constants, strings, classes, objects n midterm 2 n all of the above plus/especially: n conditionals, loops, arrays, sorting n final n all of the above plus/especially: n interfaces, inheritance n more on classes, objects n scope, static fields/methods, control flow n pass by reference vs. pass by value

8 Reading Summary n

9 Practice Exams n One practice final (without solutions) up on WebCT/Vista n Another practice exam available under Challenge link from course page

10 Exam Philosophy n my exams tend to be hard and long n thus, I almost always end up scaling marks n difficult exams can be scaled n too-easy exams cannot distinguish those who know material from those who don't n how to handle exams with deliberate time pressure n do not panic if you think you won't finish n do be strategic about how to spend your time n I recommend you look through entire exam before you jump into writing answers n spend a few minutes up front to plan best approach for your strengths

11 How To Prepare n Read all the required reading n Review lecture notes and code written in class n available from web n Practice, practice, practice -- write programs!! n especially using inheritance and abstract classes

12 Programming Practice n Two kinds of practice, both are important! n Using computer, open book, Internet, discussing approach with friends, take as long as you need to fully understand n Closed book, write on paper, don't talk to anybody about the question, time pressure

13 Head First Java by Kathy Sierra and Bert Bates Read this book, work all the problems (there are zillions), and you should have a better grasp of what's going on with Java. (I have no financial interest in this book or any bookseller.) Alternate Book n If you're not getting it and want to try a different approach, run to the bookstore (or head to Amazon.ca or Indigo.ca) and get a copy of...

14 The Coca-Cola Company has founded Vending University. VU has two kinds of students. The full time students pay $ per credit in tuition up to a maximum of $ (12 credits), even if they enroll in more than 12 credits. Tuition for students in the executive program is computed differently; these students pay a $ "executive fee" plus $ per credit, with no ceiling or cap on the total. Each student has a name and is enrolled for some integer number of credits. Write an abstract superclass called Student, and write concrete subclasses called FullTimeStudent and ExecutiveStudent. The method for computing the tuition should be called computeTuition(). Now do it again, but with an interface called Student instead of an abstract superclass. Provide a test program that uses polymorphism to test your classes and methods. Practice Problem

15 Recap: Inheritance Class Hierarchy n Is base class something that you would ever want to instantiate itself? Generic Vending Machine Coke Machine Coke Machine2000 French Fry Machine is-a Coke MachineUA is-a Pizza Machine Beer Machine is-a

16 Recap: Abstract Classes n Abstract class: not completely implemented n serve as place holders in class hierarchy n partial description inherited by all descendants n Usually contains one or more abstract methods n has no definition: specifies method that should be implemented by subclasses n just has header, does not provide actual implementation for that method n Abstract class uses abstract methods to specify what interface to descendant classes must look like n without providing implementation details for methods that make up interface n descendent classes supply additional information so that instantiation is meaningful

17 Recap: Interfaces vs. Abstract Classes n Use abstract class with inheritance to initiate a hierarchy of more specialized classes n Use interface to say, "I need to be able to call methods with these signatures in your class." n Use an interface for some semblance of multiple inheritance from Just Java 2 by Peter van der Linden

18 A (Very) Last Look At Bunnies... n interface and inheritance practice! n let's make a SortableBunny class that both n extends NamedBunny class n implements Comparable interface n compareTo(Object o) n returns int < 0 if this object less than parameter n returns 0 if same n returns int > 0 if this object greater than parameter

19 Comparing Bunnies n how to compare? n number of carrots? location?... n names - alphabetical order! n do we have to implement this from scratch? n no! use String compareTo method

20 SortableBunny public class SortableBunny extends NamedBunny implements Comparable { public SortableBunny(){ super(); } public SortableBunny(int x, int y, int carrots, String name){ super(x,y,carrots,name); } /* compare by name alphabetical order */ public int compareTo(Object other){ return this.getName().compareTo( ((SortableBunny)other).getName() ); }

21 BunnySorter public static void main(String[] args){ SortableBunny[] bunnies = new SortableBunny[4]; SortableBunny peter = new SortableBunny(3,6,1,"Peter"); SortableBunny emily = new SortableBunny(3,4,5,"Emily"); SortableBunny darlene = new SortableBunny(3,6,1,"Darlene"); SortableBunny aaron = new SortableBunny(3,4,5,"Aaron"); bunnies[0] = peter; bunnies[1] = emily; bunnies[2] = darlene; bunnies[3] = aaron; BunnySorter.sort(bunnies); }

22 BunnySorter public static void main(String[] args){ SortableBunny[] bunnies = new SortableBunny[4]; SortableBunny peter = new SortableBunny(3,6,1,"Peter"); SortableBunny emily = new SortableBunny(3,4,5,"Emily"); SortableBunny darlene = new SortableBunny(3,6,1,"Darlene"); SortableBunny aaron = new SortableBunny(3,4,5,"Aaron"); bunnies[0] = peter; bunnies[1] = emily; bunnies[2] = darlene; bunnies[3] = aaron; BunnySorter.sort(bunnies); darlene.compareTo("UhOhNotABunny"); } n crashes when we pass in String!

23 SafeSorter public static void main(String[] args){ SafeBunny[] bunnies = new SafeBunny[4]; SafeBunny peter = new SafeBunny(3,6,1,"Peter"); SafeBunny emily = new SafeBunny(3,4,5,"Emily"); SafeBunny darlene = new SafeBunny(3,6,1,"Darlene"); SafeBunny aaron = new SafeBunny(3,4,5,"Aaron"); bunnies[0] = peter; bunnies[1] = emily; bunnies[2] = darlene; bunnies[3] = aaron; SafeSorter.sort(bunnies); darlene.compareTo("UhOhNotABunny"); } n no crashes. whew....

24 SafeBunny /* compare by name alphabetical order */ /* check if it's the right type before call getName method! */ public int compareTo(Object other) { if (other instanceof SafeBunny) { return this.getName().compareTo( ((SafeBunny)other).getName() ); } else { return 0; } n solution: check type of object dynamically n before we call bunny-specific method

25 Checking Type Dynamically n A instanceof B n checks at execution time n instanceof is a reserved word n A is object n B is specific class name

26 A Final Reminder (for the Final) n designing classes vs. using classes n all of our code starts with public class Foo n designing classes n you fill in fields, method n using classes n tester/driver, with main method n examples n design: SortableBunny implements Comparable interface n use: Sorter.java code uses Integer, Double, String, SortableBunny classes and Comparable interface

27 Evaluations - Right Now n official TA evaluations n still on paper, not online yet n unofficial course evaluations n much more specific questions than the official ones n I do not look at these until after official ones returned, long after grades are out n need volunteer to collect these n bring official ones to front desk n ask receptionist to put unofficial ones in my box n in closed envelope n please also fill out official teaching surveys for instructor (me!) at the CoursEval website

28 Life After 111: What Next? n two threads in CS coursework n continuing with programming n 211: Intro to Software Development n your first taste of theory n 111: Intro to Computation n playing with computers on your own n fame, fortune, and joy!

29 Graphical User Interfaces (as much as we have time for)

30 Reading for GUIs n This week reading: , , n , 11.5, (2nd edition) n we will only get through some of this material in lecture today n not covered on final n but weekly reading question due today

31 Objectives n Taste of what's under the hood with graphical programming n note: taste, not mastery!

32 Simple Graphics This week is all about very simple graphics in Java. What we'll talk about aren't necessarily fundamental computing concepts like loops, arrays, inheritance, and polymorphism, which surface in all sorts of different computing contexts. This stuff will be Java-specific and may not translate well to other programming languages.

33 Simple Graphics The good news is that you might find graphics more fascinating than Coke Machines. The bad news is that Java graphics can become tedious very quickly.

34 Simple Graphics To begin with, we need a "canvas" or a "blank sheet of paper" on which to draw. In Java, this is called a frame window or just a frame. You don't put your graphics just anywhere you want...you draw them inside the frame. It should come as no surprise that a specific frame that we draw in will be an object of some class that serves as a template for frames. Remember, nothing much happens in Java until we create objects.

35 Making a frame window Step 1: Construct an object of the JFrame class.

36 Making a frame window import javax.swing.JFrame; //Swing is a user interface toolkit public class FrameViewer { public static void main(String[] args) { JFrame myframe = new JFrame(); // make a new JFrame object }

37 Making a frame window Step 1: Construct an object of the JFrame class. Step 2: Set the size of the frame.

38 Making a frame window import javax.swing.JFrame; public class FrameViewer { public static void main(String[] args) { JFrame myframe = new JFrame(); // make a new JFrame object final int F_WIDTH = 300; // 300 pixels wide final int F_HEIGHT = 400; // 400 pixels high myframe.setSize(F_WIDTH, F_HEIGHT); }

39 Making a frame window Step 1: Construct an object of the JFrame class. Step 2: Set the size of the frame. Step 3: Set the title of the frame to appear in the title bar (title bar will be blank if no title is set).

40 Making a frame window import javax.swing.JFrame; public class FrameViewer { public static void main(String[] args) { JFrame myframe = new JFrame(); // make a new JFrame object final int F_WIDTH = 300; // 300 pixels wide final int F_HEIGHT = 400; // 400 pixels high myframe.setSize(F_WIDTH, F_HEIGHT); myframe.setTitle("My Frame"); // this is optional }

41 Making a frame window Step 1: Construct an object of the JFrame class. Step 2: Set the size of the frame. Step 3: Set the title of the frame to appear in the title bar (title bar will be blank if no title is set). Step 4: Set the default close operation. When the user clicks the close button, the program stops running.

42 Making a frame window import javax.swing.JFrame; public class FrameViewer { public static void main(String[] args) { JFrame myframe = new JFrame(); // make a new JFrame object final int F_WIDTH = 300; // 300 pixels wide final int F_HEIGHT = 400; // 400 pixels high myframe.setSize(F_WIDTH, F_HEIGHT); myframe.setTitle("My Frame"); // this is optional myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

43 Making a frame window Step 1: Construct an object of the JFrame class. Step 2: Set the size of the frame. Step 3: Set the title of the frame to appear in the title bar (title bar will be blank if no title is set). Step 4: Set the default close operation. When the user clicks the close button, the program stops running. Step 5: Make the frame visible.

44 Making a frame window import javax.swing.JFrame; public class FrameViewer { public static void main(String[] args) { JFrame myframe = new JFrame(); // make a new JFrame object final int F_WIDTH = 300; // 300 pixels wide final int F_HEIGHT = 400; // 400 pixels high myframe.setSize(F_WIDTH, F_HEIGHT); myframe.setTitle("My Frame"); // this is optional myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myframe.setVisible(true); }

45 Making a frame window import javax.swing.JFrame; public class FrameViewer { public static void main(String[] args) { JFrame myframe = new JFrame(); // make a new JFrame object final int F_WIDTH = 300; // 300 pixels wide final int F_HEIGHT = 400; // 400 pixels high myframe.setSize(F_WIDTH, F_HEIGHT); myframe.setTitle("My Frame"); // this is optional myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when it's time to draw something in the frame, // we'll do it here myframe.setVisible(true); }

46 Making a frame window > java FrameViewer

47 Now let's draw something Wait, hold on. We don't draw anything. We create component objects (of course) and add them to the frame we've created. We make our own component in the Swing user interface toolkit by extending the blank component called JComponent to make a RectangleComponent. The paintComponent() method is inherited from JComponent, then we override the method with our own definition that makes a couple of rectangles.

48 Now let's draw something import java.awt.Graphics; // AWT is the Abstract Windowing Toolkit, import java.awt.Graphics2D; // an older graphical user interface import java.awt.Rectangle; // toolkit import javax.swing.JPanel; import javax.swing.JComponent; public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { }

49 Now let's draw something The paintComponent() method of an object is called automatically when the frame that contains it is displayed for the first time, resized, or redisplayed after being hidden.

50 Now let's draw something import java.awt.Graphics; // AWT is the Abstract Windowing Toolkit, import java.awt.Graphics2D; // an older graphical user interface import java.awt.Rectangle; // toolkit import javax.swing.JPanel; import javax.swing.JComponent; public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { }

51 Now let's draw something The paintComponent() method is passed an object of type Graphics2D, which extends the Graphics type, that contains useful information about colour and font to be used, among other things. Graphics2D provides more sophisticated methods for drawing too. But the paintComponent() method expects a parameter of the older Graphics type, so we use a cast to convert the object to Graphics2D type to recover the methods that come with the Graphics2D class.

52 Now let's draw something import java.awt.Graphics; // AWT is the Abstract Windowing Toolkit, import java.awt.Graphics2D; // an older graphical user interface import java.awt.Rectangle; // toolkit import javax.swing.JPanel; import javax.swing.JComponent; public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; }

53 Now let's draw something Now we draw a box. We give the X- and Y- coordinates of the upper left hand corner of the box, along with its width and height in pixels (i.e. picture elements).

54 Now let's draw something import java.awt.Graphics; // AWT is the Abstract Windowing Toolkit, import java.awt.Graphics2D; // an older graphical user interface import java.awt.Rectangle; // toolkit import javax.swing.JPanel; import javax.swing.JComponent; public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; Rectangle box = new Rectangle(5, 10, 50, 75); g2.draw(box); }

55 Now let's draw something The translate() method allows the programmer to start the drawing of the next box at different X- and Y- coordinates.

56 Now let's draw something import java.awt.Graphics; // AWT is the Abstract Windowing Toolkit, import java.awt.Graphics2D; // an older graphical user interface import java.awt.Rectangle; // toolkit import javax.swing.JPanel; import javax.swing.JComponent; public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; Rectangle box = new Rectangle(5, 10, 50, 75); g2.draw(box); box.translate(80,100); }

57 Now let's draw something Now we can draw the second and final box.

58 Now let's draw something import java.awt.Graphics; // AWT is the Abstract Windowing Toolkit, import java.awt.Graphics2D; // an older graphical user interface import java.awt.Rectangle; // toolkit import javax.swing.JPanel; import javax.swing.JComponent; public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; Rectangle box = new Rectangle(5, 10, 50, 75); g2.draw(box); box.translate(80,100); g2.draw(box); }

59 Now let's draw something One more thing: we have to add the rectangle component to our frame object.

60 Now let's draw something import javax.swing.JFrame; public class FrameViewer { public static void main(String[] args) { JFrame myframe = new JFrame(); // make a new JFrame object final int F_WIDTH = 300; // 300 pixels wide final int F_HEIGHT = 400; // 400 pixels high myframe.setSize(F_WIDTH, F_HEIGHT); myframe.setTitle("My Frame"); // this is optional myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RectangleComponent component = new RectangleComponent(); myframe.add(component); myframe.setVisible(true); }

61 Here's what we drew > java FrameViewer

62 Questions?

63 Graphical user interfaces (GUIs) The graphical user interface allows us to interact with our programs through mouse movements, button clicks, key presses, and so on. Your Windows or Macintosh operating system provides you with a GUI so you don't have to remember all sorts of instructions to type at the command line.

64 Graphical user interfaces (GUIs) The graphical user interface allows us to interact with our programs through mouse movements, button clicks, key presses, and so on. Your Windows or Macintosh operating system provides you with a GUI so you don't have to remember all sorts of instructions to type at the command line. Here's a GUI you've seen me use many times.

65 Event handling How do we make a GUI in Java? We install event listeners. An event listener is an object that belongs to a class which you define. The methods in your event listener contain the instructions to be executed when the events occur. Any event listener is specific to an event source. For example, you'd have one kind of event listener to respond to the click of a button on your mouse, and another to respond to the press of a key on your keyboard. When an event occurs, the event source calls the appropriate methods of all associated event listeners.

66 Event handling Here comes an example, straight from your book. This example is a simple program that prints a message when a button is clicked. An event listener that responds to button clicks must belong to a class that implements the ActionListener interface. That interface, supplied by the Abstract Windowing Toolkit (AWT), looks like this: public interface ActionListener { void actionPerformed(ActionEvent event); } Java uses the event parameter to pass details about the event. We don't need to worry about it.

67 Event handling Here's what our example class that implements the ActionListener interface looks like: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("I was clicked."); } The actionPerformed() method contains the instructions we want to be executed when our button is clicked.

68 Event handling Next we'll see a program that tests our ClickListener class. It looks very much like the program we wrote earlier. First we create a frame window object so we have a place to put the button that we want to click.

69 Event handling import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionListener; public class ButtonTester { public static void main(String[] args) { JFrame myframe = new JFrame(); final int F_WIDTH = 100; final int F_HEIGHT = 60; myframe.setSize(F_WIDTH, F_HEIGHT); myframe.setTitle("Button Tester"); myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myframe.setVisible(true); }

70 Event handling Next we'll see a program that tests our ClickListener class. It looks very much like the program we wrote earlier. First we create a frame window object so we have a place to put the button that we want to click. Then we create a button object and add it to the frame, just like the rectangles before.

71 Event handling import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionListener; public class ButtonTester { public static void main(String[] args) { JFrame myframe = new JFrame(); final int F_WIDTH = 100; final int F_HEIGHT = 60; myframe.setSize(F_WIDTH, F_HEIGHT); myframe.setTitle("Button Tester"); myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button = new JButton("Click me!"); myframe.add(button); myframe.setVisible(true); }

72 Event handling Next we'll see a program that tests our ClickListener class. It looks very much like the program we wrote earlier. First we create a frame window object so we have a place to put the button that we want to click. Then we create a button object and add it to the frame, just like the rectangles before. Finally we create an event listener object called ClickListener and attach it to the button we just made.

73 Event handling import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionListener; public class ButtonTester { public static void main(String[] args) { JFrame myframe = new JFrame(); final int F_WIDTH = 100; final int F_HEIGHT = 60; myframe.setSize(F_WIDTH, F_HEIGHT); myframe.setTitle("Button Tester"); myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button = new JButton("Click me!"); myframe.add(button); ActionListener listener = new ClickListener(); button.addActionListener(listener); myframe.setVisible(true); }

74 Event handling > java ButtonTester

75 Event handling A button listener class like ClickListener is likely to be specific to a particular button, so we don't really need it to be widely accessible. We can put the class definition inside the method or class that needs it. So we can put this class: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("I was clicked."); } inside the main method of the ButtonTester class as an inner class.

76 Event handling import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; // note this addition public class ButtonTester2 { public static void main(String[] args) { JFrame myframe = new JFrame(); final int F_WIDTH = 100; final int F_HEIGHT = 60; myframe.setSize(F_WIDTH, F_HEIGHT); myframe.setTitle("Button Tester"); myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button = new JButton("Click me!"); myframe.add(button);

77 Event handling class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("I was clicked."); } ActionListener listener = new ClickListener(); button.addActionListener(listener); myframe.setVisible(true); }