CS 106A, Lecture 24 Interactors and NameSurfer

Similar documents
CS 106A, Lecture 23 Interactors and GCanvas

Assignment 6 YEAH Hours. Ben Barnett and Avery Wang

YEAH session #6. 6 March 2014, 5:30p-6:30p Miles Seiver

CS 106A, Lecture 25 Life After CS 106A, Part 1

Interactors. Brahm Capoor.

YEAH Session #6. November 13, 2014, 6-7 PM Nick Troccoli

CS 106A, Lecture 14 Events and Instance Variables

CS 106A, Lecture 14 Events and Instance Variables

Classes. How can we manage large programs?

Section Handout #7: Interactors and Classes

Solution to Section #7

Solutions to Section #7

Section Handout #7: Interactors and Classes

CS 106A, Lecture 27 Final Exam Review 1

CS 106A, Lecture 27 Final Exam Review 1

Mehran Sahami Handout #39 CS 106A November 14, 2007 Assignment #6 NameSurfer Due: 3:15pm on Wednesday, November 28th

Memory Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

CS 106A, Lecture 11 Graphics

MIT AITI Swing Event Model Lecture 17

CS 106A, Lecture 5 Booleans and Control Flow

AP CS Unit 11: Graphics and Events

Assignment #7 FacePamphlet Due: 1:30pm on Friday, December 7th Note: No late days (free or otherwise) may be used on Assignment #7

CS 106A, Lecture 19 ArrayLists

CS 106A, Lecture 16 Arrays

CS 170 Java Programming 1. Week 9: Learning about Loops

Assignment #6 NameSurfer

CSSE 490 Model-Based Software Engineering

Assignment 6: NameSurfer

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

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

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

Section Handout #6: HashMaps, ArrayLists, and Classes

Introduction. Introduction

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

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

CS 106A, Lecture 7 Parameters and Return

Agenda. Container and Component

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

CS106A Review Session

CS 106A, Lecture 3 Problem-solving with Karel

Expressions, Statements, and Control Structures

To gain experience using GUI components and listeners.

CS 106A Winter 2017 Final Solutions

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

CS 106A, Lecture 3 Problem-solving with Karel

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

Simple Java YEAH Hours. Brahm Capoor and Vrinda Vasavada

First Name: AITI 2004: Exam 2 July 19, 2004

CS 106A, Lecture 20 ArrayLists and HashMaps

CS106A Final Exam Review Session. Saturday Dec. 10, 2016 Nick Troccoli

EVENTS, EVENT SOURCES AND LISTENERS

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

Assignment #4 Hangman Due: 11am on Monday, May 14th This assignment may be done in pairs (which is optional, not required)

CS 106X, Lecture 16 More Linked Lists

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Class 16: The Swing Event Model

Information Technology for Industrial Engineers 15 November ISE 582: Information Technology for Industrial Engineers

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Graphical User Interfaces. Comp 152

First Name: AITI 2004: Exam 2 July 19, 2004

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

Implementing Graphical User Interfaces

Assignment #4 Hangman Due: 10:30am on Friday, Febuary 17th This assignment may be done in pairs (which is optional, not required)

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

CS 106X Lecture 26: Inheritance and Polymorphism in C++

Java Programming Lecture 6

SINGLE EVENT HANDLING

Name Section. CS 21a Introduction to Computing I 1 st Semester Final Exam

Java - Applets. public class Buttons extends Applet implements ActionListener

Colin Kincaid Assignment #6 CS 106A August 6, 2018 Assignment #6 BiasBars Due: 11:00AM PDT on Tuesday, August 14 th

H212 Introduction to Software Systems Honors

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

CS111: PROGRAMMING LANGUAGE II

Programming Lecture 13

Solutions to Midterm Exam

RAIK 183H Examination 2 Solution. November 10, 2014

Lab & Assignment 1. Lecture 3: ArrayList & Standard Java Graphics. Random Number Generator. Read Lab & Assignment Before Lab Wednesday!

CS 101 Computer Programming

File: GFace.java /* * File: GFace.java * This class implements a face as a GCompound. */

CS 106A, Lecture 9 Problem-Solving with Strings

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions

Solutions to Section #6

RAIK 183H Examination 2 Solution. November 11, 2013

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Data Structure Design II Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

An array is a type of variable that is able to hold more than one piece of information under a single variable name.

Answers to Additional Practice Final Problems

Example: CharCheck. That s It??! What do you imagine happens after main() finishes?

Graphical User Interface

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.

October 27, 7:30-9:30 PM Taylor Bacon and Kashif Nazir (Based on slides by Nick Troccoli)

Programming in the Real World

Graphical User Interface (GUI)

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

CS 170 Java Programming 1. Week 10: Loops and Arrays

CS 106A, Lecture 9 Problem-Solving with Strings

Solutions for Section #2

Transcription:

CS 106A, Lecture 24 Interactors and NameSurfer suggested reading: Java Ch. 10.5-10.6 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others.

Plan for today Recap: Extending GCanvas Interactors JButton JLabel JTextField Example: TipCalculator NameSurfer 2

Plan for today Recap: Extending GCanvas Interactors JButton JLabel JTextField Example: TipCalculator NameSurfer 3

Extending GCanvas public class Graphics extends Program { public void init() { // We can make our own GCanvas! MyCanvas canvas = new MyCanvas(); add(canvas); public void run() { // Operate on this canvas GObject obj = canvas.getelementat( ); 4

Extending GCanvas public class MyCanvas extends GCanvas { public void addcenteredsquare(int size) { GRect rect = new GRect(size, size); int x = getwidth() / 2.0 rect.getwidth() / 2.0; int y = getheight() / 2.0 rect.getheight() / 2.0; add(rect, x, y); 5

Extending GCanvas public class Graphics extends Program { public void init() { // We can make our own GCanvas! MyCanvas canvas = new MyCanvas(); add(canvas); public void run() { canvas.addcenteredsquare(20); 6

Common Bugs When you are using a custom canvas, make sure to not call getwidth or getheight on the canvas until it is shown onscreen! public class MyProgram extends Program { private MyCanvas canvas; public void init() { // canvas not created yet! canvas = new MyCanvas(); // canvas not added yet! add(canvas); // window not showing yet! public void run() { // good to go 7

Example: Aquarium We used classes to make a graphical program called Aquarium that simulates fish swimming around. 8

Aquarium.java public class Aquarium extends Program { private static final int NUM_FISH = 5; private FishTank tank; public void init() { tank = new FishTank(); add(tank);... 9

Aquarium.java... public void run() { tank.initialize(); for (int i = 0; i < NUM_FISH; i++) { tank.addfish(); while (true) { tank.movefish(); pause(30); 10

FishTank.java public class FishTank extends GCanvas { private ArrayList<Fish> fish; public FishTank() { fish = new ArrayList<>(); public void initialize() { GImage background = new GImage("res/bkrnd.jpg"); background.setsize(getwidth(), getheight()); add(background);... 11

FishTank.java... public void addfish() { Fish newfish = new Fish(getWidth(), getheight()); fish.add(newfish); add(newfish.getimage()); public void movefish() { for (Fish currentfish : fish) { currentfish.swim(getwidth(), getheight()); 12

Plan for today Recap: Extending GCanvas Interactors JButton JLabel JTextField Example: TipCalculator NameSurfer 13

Interactors 14

Interactors JComponent JButton JLabel JTextField 15

Plan for today Recap: Extending GCanvas Interactors JButton JLabel JTextField Example: TipCalculator NameSurfer 16

JButton 17

JButton import java.awt.event.*; import javax.swing.*; JButton button = new JButton( Press me ); add(button, SOUTH); 18

Window Regions In graphics or console programs, the window is divided into five regions: The CENTER region is typically where the action happens. ConsoleProgram adds a console there GraphicsProgram puts a GCanvas there Other regions are visible only if you add an interactor to them using add(component, REGION); Interactors are automatically centered within each region. 19

Responding To Button Clicks To respond to events from interactors, we must do the following: 1. Call addactionlisteners() at the end of init, once we are done adding buttons. This tells Java to let us know if any of the previous buttons were clicked. 2. Implement the public actionperformed method. This method is called whenever a button is clicked. 20

JButton Example public class Interactors extends ConsoleProgram { public void init() { JButton yaybutton = new JButton("Yay"); add(yaybutton, SOUTH); JButton naybutton = new JButton("Nay"); add(naybutton, SOUTH); addactionlisteners(); public void actionperformed(actionevent event) {... //? 21

ActionEvent The ActionEvent parameter contains useful event information. Use getsource or getactioncommand to figure out what button or component was interacted with. Method e.getactioncommand() e.getsource() Description a text description of the event (e.g. the text of the button clicked) the interactor that generated the event public void actionperformed(actionevent event) { String command = event.getactioncommand(); if (command.equals("save File")) { // user clicked the Save File button... 22

JButton Example 23

JButton Example public class Interactors extends ConsoleProgram { private JButton yaybutton; private JButton naybutton; public void init() { yaybutton = new JButton("Yay"); add(yaybutton, SOUTH); naybutton = new JButton("Nay"); add(naybutton, SOUTH); addactionlisteners(); public void actionperformed(actionevent event) { if (event.getsource() == yaybutton) { println("yay"); else if (event.getsource() == naybutton) { println("nay"); 24

JButton Example #2 public class Interactors extends ConsoleProgram { private JButton yaybutton; private JButton naybutton; public void init() { JButton yaybutton = new JButton("Yay"); add(yaybutton, SOUTH); JButton naybutton = new JButton("Nay"); add(naybutton, SOUTH); addactionlisteners(); public void actionperformed(actionevent event) { if (event.getactioncommand().equals("yay")) { println("yay"); else if (event.getactioncommand().equals("nay")) { println("nay"); 25

JButton Example #2 public class Interactors extends ConsoleProgram { public void init() { JButton yaybutton = new JButton("Yay"); add(yaybutton, SOUTH); JButton naybutton = new JButton("Nay"); add(naybutton, SOUTH); addactionlisteners(); public void actionperformed(actionevent event) { println(event.getactioncommand()); 26

Plan for today Recap: Extending GCanvas Interactors JButton JLabel JTextField Example: TipCalculator NameSurfer 27

JLabel JLabel label = new JLabel("Hello, world!"); add(label, SOUTH); 28

Plan for today Recap: Extending GCanvas Interactors JButton JLabel JTextField Example: TipCalculator NameSurfer 29

JTextField JTextField field = new JTextField(10); add(field, SOUTH); 30

JTextField JTextField field = new JTextField(10); add(field, SOUTH); // Set the text in the text field field.settext("hello!"); // Get the text currently in the text field String text = field.gettext(); 31

JTextField Example 32

JTextField Example public class Interactors extends ConsoleProgram { private JTextField textfield; public void init() { textfield = new JTextField(10); add(textfield, SOUTH); JButton gobutton = new JButton("Go"); add(gobutton, SOUTH); addactionlisteners(); public void actionperformed(actionevent event) { println(textfield.gettext()); 33

Detecting ENTER Pressed Detecting the ENTER key pressed in a JTextField requires extra work. JTextField field = new JTextField(10); // Tells Java to listen for ENTER on the text field field.addactionlistener(this); // Sets the action command (like JButtons) to Go field.setactioncommand("go"); add(field, SOUTH); 34

Detecting ENTER Pressed Detecting the ENTER key pressed in a JTextField requires extra work. JTextField field = new JTextField(10); field.addactionlistener(this); field.setactioncommand("go"); add(field, SOUTH);... public void actionperformed(actionevent event) { if (event.getactioncommand().equals( Go )) {... 35

getactioncommand Oftentimes, a text field has a corresponding button that takes action with the entered text. If we set the text field s action command to be the same as its corresponding button, we can check for both a click and ENTER at once! 36

getactioncommand public void init() { JButton button = new JButton("Go"); add(button, SOUTH); JTextField field = new JTextField(10); field.addactionlistener(this); field.setactioncommand("go"); add(field, SOUTH); addactionlisteners(); public void actionperformed(actionevent event) { if (event.getactioncommand().equals( Go )) {... 37

getactioncommand public void init() { JButton button = new JButton("Go"); add(button, SOUTH); JTextField field = new JTextField(10); field.addactionlistener(this); field.setactioncommand("go"); add(field, SOUTH); addactionlisteners(); public void actionperformed(actionevent event) { if (event.getactioncommand().equals( Go )) {... 38

Plan for today Recap: Extending GCanvas Interactors JButton JLabel JTextField Example: TipCalculator NameSurfer 39

Practice: TipCalculator Let s write a program called TipCalculator that uses interactors to calculate the tip for a bill. 40

Practice: TipCalculator Let s write a program called TipCalculator that uses interactors to calculate the tip for a bill. The program should calculate the appropriate tip depending on the button the user clicks on The console should clear when a new tip is calculated (hint: use clearconsole()). Convert a string into a double using Double.parseDouble(str); 41

Plan for today Recap: Extending GCanvas Interactors JButton JLabel JTextField Example: TipCalculator NameSurfer 42

NameSurfer 43

NameSurfer Structure NameSurfer.java handles the interactors and overall program NameSurferEntry handles information about a single name and its ranks NameSurferDatabase handles information about all names and their ranks, and looks up info by name NameSurferGraph a GCanvas subclass that displays the name plots 44

NameSurfer Structure 45

NameSurfer Structure NameSurfer.java handles the interactors and overall program NameSurferEntry handles information about a single name and its ranks NameSurferDatabase handles information about all names and their ranks, and looks up info by name NameSurferGraph a GCanvas subclass that displays the name plots 46

NameSurfer Structure NameSurfer.java handles the interactors and overall program NameSurferEntry handles information about a single name and its ranks NameSurferDatabase handles information about all names and their ranks, and looks up info by name NameSurferGraph a GCanvas subclass that displays the name plots 47

NameSurferEntry Responsible for storing the data about one name/line in the text file -> name and ranks. (Hint: use a Scanner!) What instance variables does a NameSurferEntry need? Implement the following methods: public NameSurferEntry(String dataline) public String getname() public int getrank(int decadessince1900) public String tostring() 48

NameSurfer Structure NameSurfer.java handles the interactors and overall program NameSurferEntry handles information about a single name and its ranks NameSurferDatabase handles information about all names and their ranks, and looks up info by name NameSurferGraph a GCanvas subclass that displays the name plots 49

NameSurferDatabase Responsible for reading in the text file and creating/storing NameSurferEntry objects. Needs to be able to find entries given their name (case insensitive!). What data structure might be useful here? 50

NameSurferDatabase // TODO: comment this file import java.io.*; import java.util.*; public class NameSurferDatabase implements NameSurferConstants { // TODO: comment this constructor public NameSurferDatabase(String filename) { // TODO: fill this in // TODO: comment this method public NameSurferEntry findentry(string name) { // TODO: implement this method return null; // remove this line 51

NameSurfer Structure NameSurfer.java handles the interactors and overall program NameSurferEntry handles information about a single name and its ranks NameSurferDatabase handles information about all names and their ranks, and looks up info by name NameSurferGraph a GCanvas subclass that displays the name plots 52

NameSurferGraph A subclass of GCanvas that handles all the graph drawing (similar to FishTank.java in our Aquarium program) Different, cycling colors for each plot line Ranks range from 1 to 1000, with rank 0 specially marked at the bottom Tip: use the output comparison tool! 53

NameSurferGraph Rank 1 Rank 1000 AND 0 54

NameSurferGraph: Resizing 55

NameSurferGraph: Resizing Every time the window resizes, update() is called. Therefore, update() must clear and redraw the whole graph. This means the graph must store the entries being graphed so it can redraw them whenever it needs to. What might be appropriate to help us store this? Other required methods: clear() addentry(namesurferentry entry) These methods do NOT actually alter the graphics. You must call update() to do that, since update() must do all the drawing. 56

NameSurferConstants Make sure to always use the provided constants! You may add more, but add them in other files, not this provided one. 57

Recap Recap: Extending GCanvas Interactors: JButton, JLabel, JTextField Example: TipCalculator NameSurfer Next time: Life after CS 106A, Part 1 58