Good, so I'm very upset here. This piece of code is a very simple moving JComponent.
Which is strange, because when I change absolutely nothing, the keyPressed event will be incredibly inconsistent. I run the program, and sometimes it will work, and my ball will move around the screen. On the other hand, I will close it and open it without changing anything, and it will not work. I do not think that the focus here is a problem, although I really know little about it. I have no idea what is going on.
Any help would be greatly appreciated. I just donโt see how a program can so inconsistently fail and succeed.
And here is my code in the character class, because I donโt think just giving you a snippet will help. I donโt know if itโs just me or something else, but if you want to compile it and see it, go ahead.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Character extends JComponent implements KeyListener { Timer timer = new Timer(5, new TimeListener()); private int x = 250; private int y = 300; char whichTimer; public Character() { addKeyListener(this); setFocusable(true); requestFocusInWindow(); repaint(); } public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_W) { timer.stop(); } if(e.getKeyCode() == KeyEvent.VK_A) { timer.stop(); } if(e.getKeyCode() == KeyEvent.VK_S) { timer.stop(); } if(e.getKeyCode() == KeyEvent.VK_D) { timer.stop(); } } public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_W) { timer.stop(); whichTimer = 'W'; timer.start(); } if(e.getKeyCode() == KeyEvent.VK_A) { timer.stop(); whichTimer = 'A'; timer.start(); } if(e.getKeyCode() == KeyEvent.VK_S) { timer.stop(); whichTimer = 'S'; timer.start(); } if(e.getKeyCode() == KeyEvent.VK_D) { timer.stop(); whichTimer = 'D'; timer.start(); } } public void keyTyped(KeyEvent e) { } protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g;
source share