View Single Post
  #1 (permalink)  
Old 03-18-2008, 12:32 PM
adam405 adam405 is offline
Member
 
Join Date: Mar 2008
Posts: 7
adam405 is on a distinguished road
moving slider with key event
I have a rectangle drawn on the screen. I can move it one instance to the right and one left. I want to be able to move it right across the applet screen. Where am i going wrong

Code:
import java.applet.*; import java.awt.*; import java.awt.Graphics; public class slider extends Applet implements Runnable { int x_pos = 30; int y_pos = 100; int x_speed = 1; int radius = 20; int appletsize_x = 300; int appletsize_y = 300; // Variablen für die Doppelpufferung private Image dbImage; private Graphics dbg; Thread thread; boolean run = false; public void start () { // define a new thread run = true; thread = new Thread (this); // start this thread thread.start (); System.out.println("start"); } public void stop() { run = false; if(thread != null) thread.interrupt(); thread = null; System.out.println("stop"); } public boolean keyDown (Event e, int key) { // linke Cursortaste if (key == Event.LEFT) { // Ball bewegt sich dann nach links x_speed = -1; x_pos += x_speed; } // rechte Cursortaste else if (key == Event.RIGHT) { // Ball bewegt sich dann nach rechts x_speed = +1; x_pos += x_speed; } // SpaceBar hat Wert 32 else { // Ausgabe von gedrüktem Key und Zahlenwert an die Standardausgabe System.out.println ("Charakter: " + (char)key + " Integer Value: " + key); } return true; } public void run () { // Erniedrigen der ThreadPriority um zeichnen zu erleichtern Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // Solange true ist läuft der Thread weiter while (run) { x_pos = x_speed; repaint(); try { // Stoppen des Threads für in Klammern angegebene Millisekunden Thread.sleep (5); } catch (InterruptedException ex) { // do nothing } // Zurücksetzen der ThreadPriority auf Maximalwert Thread.currentThread().setPriority(Thread.MAX_PRIORITY); } } /** Update - Methode, Realisierung der Doppelpufferung zur Reduzierung des Bildschirmflackerns */ public void update (Graphics g) { // Initialisierung des DoubleBuffers if (dbImage == null) { dbImage = createImage (this.getSize().width, this.getSize().height); dbg = dbImage.getGraphics (); } // Bildschirm im Hintergrund löschen dbg.setColor (getBackground ()); dbg.fillRect (0, 0, this.getSize().width, this.getSize().height); // Auf gelöschten Hintergrund Vordergrund zeichnen dbg.setColor (getForeground()); paint (dbg); // Nun fertig gezeichnetes Bild Offscreen auf dem richtigen Bildschirm anzeigen g.drawImage (dbImage, 0, 0, this); } public void paint (Graphics g) { Graphics2D g2 = (Graphics2D) g; Rectangle box = new Rectangle(x_pos,y_pos,60,25); g2.draw(box); } }
Reply With Quote
Sponsored Links