Download - Java Applets for Experiments NSF Workshop, UC-Fullerton Gary McClelland 10-13 August 2003
Java Workshop Outline
Java, what it is and isn’tObject-Oriented Programming (OOP)First applet: HelloWorldGraphics drawingListening for events
mouse, keys, Buttons, Scrollbars
Java ≠ JavascriptJavascript
HTML scripting languageFormsInterpreted
JavaApplets embedded in HTML pageStandalone applicationsComplete programming languageCompiled
Java’s Goods & Bads
StrengthsGraphicsInteractivity (mouse, keys, scrollbars)Precise control
WeaknessesTiming at the ms level (some debate)Learning curve
History of an Applet
Edit java source code & htmlnotepad Hello.javanotepad Hello.html
Compile source to ByteCodesjavac Hello.javaproduces Hello.class
View applet (Java Virtual Machine)appletviewer Hello.htmlbrowser Hello.html
Integrated Development Environment (IDE):
JBuilderEditor
Syntax checkingCommand completionAutomatic compilation
HTML ViewerSwitch form editor to browser view
Object-Oriented Programming (OOP)
ObjectsState VariablesBehavior Methods
CarState: running, speed, locationBehavior: brake, accelerate,
changeGear, start, stop
Java class: object blueprint
Class variablesConstructor (object “factory”)Methods (subroutine definitions)
Interface
CarBrake pedalGas pedalSteering wheelTurn signal lever
MouseMotionListenerpublic void mouseMoved(MouseEvent me)public void mouseDragged(MouseEvent me)
Encapsulation
CarHow brakes and engine work can be a
mystery
Java Objectprivate methodsWe don’t need to know how they work
Card Constructor
Card(String s1, Color c1, String s2, Color c2, int fontSize)s1: text on “front” of cardc1: color on “front” of cards2: text on “reverse” of card after clickc2: color on “reverse” of card after clickfontSize: size of font for both Strings
Using Card in Wason Task
public void init() { setLayout(new GridLayout(1,4,20,0)); add(new Card("E",Color.white,"E",Color.yellow,24)); add(new Card("K",Color.white,"K",Color.yellow,24)); add(new Card("4",Color.white,"4",Color.yellow,24)); add(new Card("5",Color.white,"5",Color.yellow,24)); repaint();}
Wason Task with Feedback
public void init() { setLayout(new GridLayout(1,4,20,0)); add(new Card("E",Color.white,"E",Color.green,24)); add(new Card("K",Color.white,"K",Color.red,24)); add(new Card("4",Color.white,"4",Color.red,24)); add(new Card("5",Color.white,"5",Color.green,24)); repaint();}
Diagnosis Codepublic void init() { int rows = 20; int cols = 20; int n = rows * cols; int pos = (38*n)/100; //38% of tests are positive int neg = n - pos; setLayout(new GridLayout(rows,cols,5,5)); int cpos = (80*pos)/100; //80% of pos are true pos int cneg = pos - cpos; for(int i=1; i<=pos; i++) { if(Math.random() < (double)cpos/(double)(cpos+cneg)) { add(new Card("M+",Color.yellow,"C+",Color.red,12)); cpos = cpos - 1; }
else { add(new Card("M+",Color.yellow,"C-",Color.green,12)); cneg = cneg - 1; } }
Diagnosis Code, Part 2 cpos = (20*pos)/100; //20% of negs are false pos cneg = neg - cpos;
for(int i=pos+1; i<=n; i++) { if(Math.random() < (double)cpos/(double)(cpos+cneg)) { add(new Card("M-",Color.white,"C+",Color.red,12)); cpos = cpos - 1; } else { add(new Card("M-",Color.white,"C-",Color.green,12)); cneg = cneg - 1; } } repaint();
}
History of an Applet
Edit java source code & htmlnotepad Hello.javanotepad Hello.html
Compile source to ByteCodesjavac Hello.javaproduces Hello.class
View applet (Java Virtual Machine)appletviewer Hello.htmlbrowser Hello.html
<html><body>
<applet code=“Hello.class”width=“300” height=“300”>
</applet>
</body></html>
Save as Hello.html
import java.awt.Applet;
public class Hello extends Applet {
public void init() { repaint(); }
public void paint(Graphics g) { g.drawString(“Hello World!”,30,30); }
}
import java.awt.Applet;
public class Hello extends Applet {
public void init() { repaint(); }
public void paint(Graphics g) { g.drawString(“Hello World!”,30,30); }
} Save as Hello.java
History of an Applet
Edit java source code & htmlnotepad Hello.javanotepad Hello.html
Compile source to ByteCodesjavac Hello.javaproduces Hello.class
View applet (Java Virtual Machine)appletviewer Hello.htmlbrowser Hello.html
History of an Applet
Edit java source code & htmlnotepad Hello.javanotepad Hello.html
Compile source to ByteCodesjavac Hello.javaproduces Hello.class
View applet (Java Virtual Machine)appletviewer Hello.htmlbrowser Hello.html
Graphics Methods: Size
getSize().width;int wd = getSize().width;
getSize().height;int ht = getSize().height;
g.drawRect(0,0,wd,ht);draws largest possible rectangle
g.drawString(“Center”,wd/2, ht/2);
Graphics Methods: Shapes
g.drawRect(x,y,w,h);g.fillRect(x,y,w,h);g.drawOval(x,y,w,h);g.fillOval(x,y,w,h);g.drawLine(x1,y1,x2,y2);
Graphics: More Shapes
g.drawPolygon(xPts,yPts,nPts);g.fillPolygon(xPts,yPts,nPts);g.drawArc(x,y,w,h,startAngle,endAngle
);g.fillArc(x,y,w,h,startAngle,endAngle);
Graphics Methods: Colors
g.setColor(Color.black);Color.red, Color.blue, Color.green,
Color.orange, Color.magenta, others…
g.setColor(new Color(r, g, b));0 ≤ r ≤ 2550 ≤ g ≤ 2550 ≤ b ≤ 255
setBackground(Color.yellow);
Graphics Methods: Fonts
g.setFont(new Font(font, style, size));Fonts: “Helvetica” “Courier” “Times”Style: Font.PLAIN, Font.BOLD,
Font.ITALICSize: any integer
g.drawString(string, x, y);
FontMetrics
FontMetrics fm;fm=getFontMetrics(getFont());int len = fm.stringWidth(“Center”);int fht = fm.getHeight();g.drawString(“Center”, wd/2-len/2,
ht/2+fht/2);
Arrays
int x[] = new int[3];Note: arrays start at 0Above creates x[0], x[1], x[2]
double y[] = new double[5];Card cards[][];
cards = new Card[20][10];cards[2][3] = new Card();
MouseListener
Object implements an interfacepublic class MouseDemo extends
Applet implements MouseListener {
Object registers to listen for eventsaddMouseListener(this);
MouseListener Methods
Object must have these methodspublic void mouseClicked(MouseEvent me)public void mousePressed(MouseEvent me)public void mouseReleased(MouseEvent
me)public void mouseEntered(MouseEvent me)public void mouseExited(MouseEvent me)
Saving Data via cgi
//send data to server//data saved locally in String dataString; public void recordData() {try { Socket t = new Socket("samiam.colorado.edu",80);
DataOutputStream out = new DataOutputStream(t.getOutputStream());
Constructing (Faking) POST
out.writeBytes( "POST "+ "http://www.myuni.edu/scripts/saveData.cgi" + " HTTP/1.0\r\n");out.writeBytes( "Content-type: application/octet-stream\r\n");out.writeBytes( "Content-length: " + dataString.length() + "\r\n\r\n");out.writeBytes(dataString);
Remainder of recordData()
t.close(); //close Socket to server
} catch(IOException e) {System.out.println("Error" + e); } } }
recordData() complete public void recordData() { //send data to server try { Socket t = new Socket(”www.myuni.edu",80); DataOutputStream out = new DataOutputStream(t.getOutputStream()); out.writeBytes( "POST "+ "http://www.myuni.edu/scripts/saveData.cgi"+ " HTTP/1.0\r\n"); out.writeBytes("Content-type: application/octet-stream\r\n"); out.writeBytes( "Content-length: " + dataString.length() + "\r\n\r\n"); out.writeBytes(dataString); t.close(); } catch(IOException e) {System.out.println("Error" + e); } } }
Object-Oriented JavascriptObjects
WindowDocumentFrameFormRadioButtonLinkURL
Properties;ocationnamevalueopener
Methodsopen()close()write()submit()
Object Syntax
object.propertycar.speed [= 30 mph]window.location [current URL]
object.method()car.accelerate(40) [speed up to 40
mph]window.close() [close this window]
StoryMaker Illustrates:
Constructing web pages on the flyInvisible to search enginesControl experiment flow
(e.g., no back button)
Pop-up windowsDialog boxesHintsInstructions
Tree of “StoryMaker”
documentwriteStory (function)storyInfo (form)
nn (textbox for name)value
birth (textbox for birth place)value
Sex[0] (radio button for male)checked
Sex[1] (radio button for female)checked