Java Reference
In-Depth Information
Figure 9. Code segment for KeyBoardBehavior.java
1.
public class KeyBoardBehaviour extends Applet
2.
{
3.
private static final int
4.
UP = KeyEvent.VK_UP, DOWN = KeyEvent.VK_DOWN, LEFT = KeyEvent.VK_LEFT,
5.
RIGHT = KeyEvent.VK_RIGHT, MOVEUP = KeyEvent.VK_W, MOVEDWN = KeyEvent.VK_S,
6.
MOVERGT = KeyEvent.VK_D, MOVELEFT = KeyEvent.VK_A;
7.
8.
private WakeupCriterion events[] = new WakeupCriterion[1];
9.
private WakeupOr allEvents;
10.
11.
public class SimpleBehavior extends Behavior
12.
{
13.
private TransformGroup targetTG;
14.
private Transform3D tempRotation = new Transform3D();
15.
private Transform3D rotation = new Transform3D();
16.
private Transform3D trans = new Transform3D();
17.
private double anglex = 0.0, angley = 0.0, TransX = 0.0, TransY = 0.0;
18.
19.
SimpleBehavior(TransformGroup targetTG) this.targetTG = targetTG;
20.
21.
public void initialize()
22.
{
23.
events[0]=new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED);
24.
this.wakeupOn(new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED));
25.
allEvents=new WakeupOr(events);
26.
wakeupOn(allEvents);
27.
}
28.
29.
public void processStimulus(Enumeration criteria)
30.
{
31.
WakeupCriterion wakeup; AWTEvent[] event ;
32.
while(criteria.hasMoreElements())
33.
{
34.
wakeup = (WakeupCriterion) criteria.nextElement();
35.
if(wakeup instanceof WakeupOnAWTEvent)
36.
{
37.
event = ((WakeupOnAWTEvent)wakeup).getAWTEvent();
38.
keyPressed((KeyEvent)event[0]);
39.
40.
}
41.
}
42.
this.wakeupOn(allEvents);
43.
}
44.
} //end of class SimpleBehavior
and so on. Lines 12 to 56 build the MoveRight behavior class to shift the object right, and
this is initialized by a WakeupOnAWTEvent. When a key is pressed, its processStimulus
method is invoked and the object is shifted right using WakeupOnElaspedFrame. Once
Search WWH ::




Custom Search