applications of java to physics teaching (part ii)

21
Applications of Java Applications of Java to to Physics Teaching (Part Physics Teaching (Part II) II) S S Tong S S Tong Department of Physics Department of Physics CUHK CUHK

Upload: ross

Post on 14-Feb-2016

35 views

Category:

Documents


2 download

DESCRIPTION

Applications of Java to Physics Teaching (Part II). S S Tong Department of Physics CUHK. 6. Simple Animations. Animations many frames displayed in a given order Thread part of the program running on its own multi-tasking ( actually multi-threading) How to create a thread? - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Applications of Java to  Physics Teaching (Part II)

Applications of Java to Applications of Java to Physics Teaching (Part II)Physics Teaching (Part II)

S S TongS S TongDepartment of PhysicsDepartment of Physics

CUHKCUHK

Page 2: Applications of Java to  Physics Teaching (Part II)

6. Simple Animations Animations

– many frames displayed in a given order Thread

– part of the program running on its own– multi-tasking (actually multi-threading)

How to– create a thread? – display the frames?– terminate the thread under certain conditions?

Page 3: Applications of Java to  Physics Teaching (Part II)

Implement the interface Runnable Declare a Thread

public class Spin extends Applet implements Runnable {Thread runner = null;......

}

Create and run a Threadrunner = new Thread(this);runner.start();

Load a series of imagefor (int i = 0; i < 16; i++)

spin[i] = getImage(getCodeBase(), "images/Spin" + i + ".gif");

calls the run() method

Page 4: Applications of Java to  Physics Teaching (Part II)

Create a loop, call the paint method repeatedlypublic void run() {

int i = 0;while (runner != null) {

currentImage = spin[i];repaint();i++;if (i > 15) i = 0;pause(50);

}}

public void paint(Graphics screen) {if (currentImage != null) {

screen.drawImage(currentImage, 100, 100, this);

......}

}

Page 5: Applications of Java to  Physics Teaching (Part II)

Flow of the applet

run()

loop insidewhile (...) { ......}

paint(...)

draw images

runner.start()

repaint()

init()

imagesloaded...getImage(...)

Thread created and initialized...new Thread(this)

call paint(...)once

Stop a threadrunner.stop();runner = null;

Page 6: Applications of Java to  Physics Teaching (Part II)

Reduce flickering– Override the update(...) method, so that the screen

is not erased before repainting

– Create an off-screen image and a Graphics object• do all drawing on the off-screen image first• replace the on-screen image with the updated off-screen

image

......Graphics offScreen;Image offScreenImage;

public void init() {offScreenImage = createImage(300,300);

......

public void update(Graphics screen) {paint(screen);

} call the paint method directly

Page 7: Applications of Java to  Physics Teaching (Part II)

Reduce flickering (contiune)public void paint(Graphics screen) {

j++;

offScreen = offScreenImage.getGraphics();if (currentImage != null) {

offScreen.setColor(Color.white);offScreen.fillRect(0,0,300,300);offScreen.drawImage(currentImage,

100, 100, this);offScreen.setColor(Color.red);offScreen.drawString("Frame no " + j,

30, 30);screen.drawImage(offScreenImage,

0, 0, this);}

}

associate the off-screen image and Graphics

erasing off-screen

drawing off-screen

put the off-screenimage on-screen

Page 8: Applications of Java to  Physics Teaching (Part II)

7 Building simple interface Basic components

Label

Button

Checkbox

Choice

TextField

Page 9: Applications of Java to  Physics Teaching (Part II)

Adding components to an applet– Declare the object type

theButton = new Button("I am a button");

theCheckbox = new Checkbox("I am a checkbox");

theChoice = new Choice();theChoice.add("I am item 1");theChoice.add("I am item 2");theChoice.add("I am item 3");

theField = new TextField("long field", 20);

Button theButton;Checkbox theCheckbox;Choice theChoice;TextField theField;

– Assign labels and attributes to the components

items

lengthcontents

– Add the components to the appletadd(...);

Page 10: Applications of Java to  Physics Teaching (Part II)

Canvas - an area for drawing– create a subclass of Canvas

class MyCanvas extends Canvas {

MyCanvas() {setBackground(Color.cyan);setSize(300,300);

}

public void paint(Graphics screen) {......

}}

– create an instance of this subclass in the applet

canvas = new MyCanvas();

draw something on the canvas

set background color

set size

– repaint the canvas

canvas.repaint();

Page 11: Applications of Java to  Physics Teaching (Part II)

How to arrange the components?– Use Layout Manager

We discuss the BorderLayout() only

public void init() {setLayout(new BorderLayout());......

North

South

Center EastWest

Page 12: Applications of Java to  Physics Teaching (Part II)

– Adding components

add("South", buttonA);add("Center", canvasB);

– Using a panel

Panel p = new Panel();

p.add(theLabel);p.add(theButton);......add("South",p)

add("Center", canvas);

Page 13: Applications of Java to  Physics Teaching (Part II)

Firing events from the components– Listeners:

ActionListener for Button

ItemListener for Choice and Checkbox

– Implementing the Listeners

import java.awt.event.*;

public class EventTest extends Applet implements ActionListener, ItemListener { ......

Listeners are interfaces

– Adding Listeners to the componentbutton1.addActionListener(this);theChoice.addItemListener(this); theCheckbox.addItemListener(this);

Page 14: Applications of Java to  Physics Teaching (Part II)

public void itemStateChanged(ItemEvent evt) {if (evt.getSource() == theChoice) { int itemNo = theChoice.getSelectedIndex();

.......if (evt.getSource() == theCheckbox) { boolean boxState = theCheckbox.getState();

.......

– Buttons trigger the actionPerformed methodpublic void actionPerformed(ActionEvent evt) {

if (evt.getSource() == button1) ......if (evt.getSource() == button2) ......canvas.repaint();

} identify which component triggers the event

– Choice menus and checkboxes trigger itemStateChanged method

get the index of the selected item

get the state (true/false) of the checkbox

Page 15: Applications of Java to  Physics Teaching (Part II)

– Updating the canvasimport java.awt.event.*;........public class EventTest extends Applet implements

ActionListener, ItemListener {

String currentString = "";......

public void actionPerformed(ActionEvent evt) {...... canvas.repaint();

}

public void itemStateChanged(ItemEvent evt) {...... canvas.repaint();

}

class EventCanvas extends Canvas {.......screen.drawString(currentString, 50, 50);......

}}

EventCanvas is defined inside EventTest- an inner class

Page 16: Applications of Java to  Physics Teaching (Part II)

class MyTextField extends TextField {

MyTextField(String s, int l) {super(s,l);

}

double getNumber() {return Double.valueOf(

getText()).doubleValue();}void setNumber(double num) {

setText(String.valueOf(num));}

}

Number I/O for a TextFieldfield.getText() gives the text of field

field.setText("string") sets the text of field to "string"

– Converting numbers to strings and vice versa

call to thesuperclass'sconstructor

string double

double string

Page 17: Applications of Java to  Physics Teaching (Part II)

Example AnimateWaves.java– superposition of two waves– amplitude, wavelengths, periods read from text fields– mode of display - choice menu– start and stop - buttons

Exercise ProjectileEx.java– initial position and velocity read from text fields– start and reset - buttons

Example ShootHead.java– Modification of Projectile.java– Shooting a free-falling object

Page 18: Applications of Java to  Physics Teaching (Part II)

Listening to mouse events– Listeners:

MouseListener mouse pressed, released, enter, exit

MouseMotionListener mouse moved, dragged

– Implementing the Listeners

import java.awt.event.*;

public class EventTest extends Applet implements MouseListener,

MouseMotionListener { ......

– Adding Listeners to the componentcanvas.addMouseListener(this);canvas.addMouseMotionListener(this);

Listeners are interfaces

Page 19: Applications of Java to  Physics Teaching (Part II)

– Let the canvas listens to mouse events– Interact with hot spots, drag and drop objects etc.

public void mouseMoved(MouseEvent evt) {...}

public void mouseDragged(MouseEvent evt) {...}

public void mousePressed(MouseEvent evt) {...}

public void mouseClicked(MouseEvent evt) {...}

public void mouseReleased(MouseEvent evt) {...}

public void mouseEntered(MouseEvent evt) {...}

public void mouseExited(MouseEvent evt) {...}

– Mouse motion events trigger

– Mouse events trigger

– Gets the mouse position inside this methods e.g.,

Point p = evt.getPoint();

Page 20: Applications of Java to  Physics Teaching (Part II)

Example AddVectors.java– addition and subtraction of two vectors– changing the text fields updates the screen– dragging the vectors updates the text fields

Page 21: Applications of Java to  Physics Teaching (Part II)

8 References L. Lemay and R. Cadenhead, Teach Yourself Java 2 in 21

days, SAMS M. Campione and K. Walrath, The Java Tutorial (2nd Ed),

Addison Wesley http://java.sun.com/