Note that there are some explanatory texts on larger screens.

plurals
  1. POJava - KeyListener Events not firing
    primarykey
    data
    text
    <p>I have begun to write a simple platform game in java. As a test, I wrote this simple program that moves a rectangle around the applet when you press the arrow keys. The key events have not been firing at all. Here's the code:</p> <pre><code>import java.applet.*; import java.awt.*; import java.awt.event.*; public class Game extends Applet implements Runnable, KeyListener { //setup data Thread t; Image buffimg; Graphics draw; Dimension dim; //game variables int charx = 400;//rectangles X and Y positions int chary = 50; boolean leftArrow = false; public void init() { setSize(800, 500); t = new Thread(this); t.start(); addKeyListener( this ); } public void run() { while(true) { repaint(); moveChar();//move the rectangle try { t.sleep(1000/30); } catch (InterruptedException e) { ; } } } public void keyPressed( KeyEvent e ) { int k = e.getKeyCode(); if(k == 37) { leftArrow = true; charx--; } } public void keyReleased( KeyEvent e ) { if(e.getKeyCode() == 37) { leftArrow = false; } } public void keyTyped( KeyEvent e ) { } public void moveChar() { //move rectangle on left arrow key press if(leftArrow == true) { charx--; } } public void paint(Graphics g) { g.drawRect(charx, chary, 100, 100); } public void update (Graphics g) { //double buffering // initialize buffer if (buffimg == null) { buffimg = createImage (this.getSize().width, this.getSize().height); draw = buffimg.getGraphics (); } // clear screen in background draw.setColor (getBackground ()); draw.fillRect (0, 0, this.getSize().width, this.getSize().height); // draw elements in background draw.setColor (getForeground()); paint (draw); // draw image on the screen g.drawImage (buffimg, 0, 0, this); } } </code></pre> <p>Why aren't they firing and how should I fix this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload