Introduction to CS 106A Eric Roberts CS 106A January 4, 2009.
CS 106A, Lecture 23 GCanvasand Interactorsweb.stanford.edu/class/archive/cs/cs106a/cs106a... · 1....
Transcript of CS 106A, Lecture 23 GCanvasand Interactorsweb.stanford.edu/class/archive/cs/cs106a/cs106a... · 1....
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture23GCanvas andInteractors
suggestedreading:JavaCh.10.5-10.6
2
Plan for today•Recap:Inheritance•ExtendingGCanvas•Example:Aquarium•Interactors–JButton–JLabel–JTextField
•Example:TipCalculator
3
Plan for today•Recap:Inheritance•ExtendingGCanvas•Example:Aquarium•Interactors–JButton–JLabel–JTextField
•Example:TipCalculator
4
Inheritance
Inheritanceletsusrelateourvariable
typestooneanother.
5
Inheritance
Employee
Programmer
KarelProgrammer
Variabletypescanseemto“inherit”fromeachother.Wedon’twanttohavetoduplicatecodeforeachone!
6
Using Inheritancepublic class Name extends Superclass {
– Example:
public class Programmer extends Employee {...
}
• ByextendingEmployee,thistellsJavathatProgrammer candoeverythinganEmployeecando,plusmore.
• ProgrammerautomaticallyinheritsallofthecodefromEmployee!• ThesuperclassisEmployee,thesubclass isProgrammer.
7
Example: Programmerpublic class Programmer extends Employee {
private int timeCoding;...public void code() {
timeCoding += 10;}
}
...
Programmer rishi = new Programmer(“Rishi”);rishi.code(); // from Programmerrishi.promote(); // from Employee!
8
Example: KarelProgrammerpublic class KarelProgrammer extends Programmer {
private int numBeepersPicked();...public void pickBeepers() {
numBeepersPicked += 2;}
}
...KarelProgrammer nick = new KarelProgrammer(“Nick”);nick.pickBeepers(); // from KarelProgrammernick.code(); // from Programmer!nick.promote(); // From Employee!
9
Plan for today•Recap:Inheritance•ExtendingGCanvas•Example:Aquarium•Interactors–JButton–JLabel–JTextField
•Example:TipCalculator
10
GCanvas• AGCanvas isthecanvasareathatdisplaysallgraphicalobjectsinaGraphicsProgram.
• WhenyoucreateaGraphicsProgram,itautomaticallycreatesaGCanvas foritself,putsitonthescreen,andusesittoaddallgraphicalshapes.
• GCanvas istheonethatcontainsmethodslike:– getElementAt– add– getWidth– getHeight– …
11
GCanvaspublic class Graphics extends GraphicsProgram {
public void run() {// A GCanvas has been created for us!GRect rect = new GRect(50, 50);add(rect); // adds to the GCanvas!
...// Checks our GCanvas for elements!GObject obj = getElementAt(25, 25);
}}
12
Extending GCanvaspublic class Graphics extends Program {
public void run() {// We have to make our own GCanvas nowMyCanvas canvas = new MyCanvas();add(canvas);
// Operate on this canvasGObject obj = canvas.getElementAt(…);
}}
13
Extending GCanvaspublic 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);
}}
14
Extending GCanvaspublic class Graphics extends Program {
public void run() {// We have to make our own GCanvas nowMyCanvas canvas = new MyCanvas();add(canvas);
canvas.addCenteredSquare(20);}
}
15
Extending GCanvas•Sometimes,wewanttobeabletohaveallofourgraphics-relatedcodeinaseparatefile.
•Todothis,insteadofusingtheprovidedGraphicsProgram canvas,wedefineourownsubclassofGCanvas, haveourprogramextendProgram,andaddourowncanvasourselves.
•Then,allgraphics-relatedcodecangoinourGCanvas subclass.
16
The init method• init isaspecialpublicmethod,likerun,thatiscalledwhenyourprogramisbeinginitialized.
• Unlikerun,however,itiscalledbefore yourprogramlaunches,lettingyoudoanyinitializationyouneed.
public class MyProgram extends GraphicsProgram {public void init() {
// executed before program launches}
public void run() {// executed after program launches
}}
17
The init method• init istypicallyusedtoinitializegraphicalcomponents,suchasaddingacustomGCanvas tothescreen.
public class MyProgram extends Program {private MyCanvas canvas;public void init() {
canvas = new MyCanvas();add(canvas);
}
public void run() {canvas.addCenteredSquare(20);
}}
18
Common Bugs• Whenyouareusingacustomcanvas,makesuretonotcallgetWidth orgetHeight onthecanvasuntilitisshownonscreen!
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
}}
19
Plan for today•Recap:Inheritance•ExtendingGCanvas•Example:Aquarium•Interactors–JButton–JLabel–JTextField
•Example:TipCalculator
20
Example: Aquarium• Let’swriteagraphicalprogramcalledAquarium thatsimulatesfishswimmingaround.
• Todecomposeourcode,wecanmakeourownGCanvas subclass.
21
Plan for today•Recap:Inheritance•ExtendingGCanvas•Example:Aquarium•Interactors–JButton–JLabel–JTextField
•Example:TipCalculator
22
Interactive ProgramsSofar,wehavelearnedabouttwowaysofmakinginteractiveprograms:• ReadinguserinputinConsolePrograms•DetectingmouseeventsinGraphicsPrograms
Today,we’regoingtolearnaboutathird:interactors.
23
Interactors
24
Interactors
JComponent
JButton
JTextFieldJLabel
25
Plan for today•Recap:Inheritance•ExtendingGCanvas•Example:Aquarium•Interactors–JButton–JLabel–JTextField
•Example:TipCalculator
26
JButton
27
JButtonimport java.awt.event.*;import javax.swing.*;
JButton button = new JButton(“Press me”);add(button, SOUTH);
28
Window Regions• Ingraphicsorconsoleprograms,thewindowisdividedintofiveregions:
• TheCENTER regionistypicallywheretheactionhappens.– ConsoleProgram addsaconsolethere– GraphicsProgram putsaGCanvas there
• Otherregionsarevisibleonlyifyouaddaninteractortothemusingadd(component, REGION);
• Interactorsareautomaticallycenteredwithineachregion.
29
Responding To Button ClicksTorespondtoeventsfrominteractors,wemustdothefollowing:1. CalladdActionListeners() attheendofinit,onceweare
doneaddingbuttons.ThistellsJavatoletusknowifanyofthepreviousbuttonswereclicked.
2. ImplementthepublicactionPerformedmethod.Thismethodiscalledwheneverabuttonisclicked.
30
JButton Examplepublic 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) {... // ?
}}
31
ActionEvent• TheActionEvent parametercontainsusefuleventinformation.
– UsegetSource orgetActionCommand tofigureoutwhatbuttonorcomponentwasinteractedwith.
public void actionPerformed(ActionEvent event) {String command = event.getActionCommand();if (command.equals("Save File")) {
// user clicked the Save File button...
}}
Method Descriptione.getActionCommand() atextdescriptionoftheevent
(e.g.thetextofthebuttonclicked)e.getSource() theinteractorthatgeneratedtheevent
32
JButton Example
33
JButton Examplepublic 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");}
}}
34
JButton Examplepublic 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");}
}}
35
JButton Examplepublic 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");}
}}
36
JButton Examplepublic 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");}
}}
37
JButton Examplepublic 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");}
}}
38
JButton Examplepublic 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");}
}}
39
JButton Example #2public 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");}
}}
40
JButton Example #2public 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) {println(event.getActionCommand());
}}
41
Plan for today•Recap:Inheritance•ExtendingGCanvas•Example:Aquarium•Interactors–JButton–JLabel–JTextField
•Example:TipCalculator
42
JLabel
JLabel label = new JLabel("Hello, world!");add(label, SOUTH);
43
Plan for today•Recap:Inheritance•ExtendingGCanvas•Example:Aquarium•Interactors–JButton–JLabel–JTextField
•Example:TipCalculator
44
JTextField
JTextField field = new JTextField(10);add(field, SOUTH);
45
JTextField
JTextField field = new JTextField(10);add(field, SOUTH);
// Set the text in the text fieldfield.setText("Hello!");
// Get the text currently in the text fieldString text = field.getText();
46
JTextField Example
47
JTextField Examplepublic 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());
}}
48
Detecting ENTER PressedDetectingtheENTERkeypressedinaJTextField requiresextrawork.
JTextField field = new JTextField(10);// Tells Java to listen for ENTER on the text fieldfield.addActionListener(this);// Sets the action command (like JButtons) to “Go”field.setActionCommand("Go");add(field, SOUTH);
49
Detecting ENTER PressedDetectingtheENTERkeypressedinaJTextField requiresextrawork.
JTextField field = new JTextField(10);field.addActionListener(this);field.setActionCommand("Go");add(field, SOUTH);
...public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals(“Go”)) {...
}}
50
getActionCommand
Oftentimes,atextfieldhasa“corresponding”buttonthattakesactionwiththeenteredtext.Ifwesetthetextfield’sactioncommandtobethesame asitscorrespondingbutton,wecancheckfor
bothaclickandENTERatonce!
51
getActionCommandpublic 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”)) {
...}
}
52
getActionCommandpublic 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”)) {
...}
}
53
Plan for today•Recap:Inheritance•ExtendingGCanvas•Example:Aquarium•Interactors–JButton–JLabel–JTextField
•Example:TipCalculator
54
Practice: TipCalculatorLet’swriteaprogramcalledTipCalculator thatusesinteractorstocalculatethetipforabill.
55
Practice: TipCalculatorLet’swriteaprogramcalledTipCalculator thatusesinteractorstocalculatethetipforabill.• Theprogramshouldcalculatetheappropriatetipdependingonthebuttontheuserclickson
• Theconsoleshouldclearwhenanewtipiscalculated(hint:useclearConsole()).
• ConvertastringintoadoubleusingDouble.parseDouble(str);
56
Recap•Recap:Inheritance•ExtendingGCanvas•Example:Aquarium•Interactors:JButton,JLabel,JTextField•Example:TipCalculator
Nexttime:NameSurfer overview