Reputation: 76
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class Game extends JFrame implements KeyListener
{
private int charX;
private int charY;
public Game()
{
charX = 250;
charY = 450;
this.setSize(500, 500);
addKeyListener(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void keyTyped(KeyEvent event)
{
if(event.getKeyChar() == 'a')
charX-=5;
else if(event.getKeyChar() == 'd')
charX+=5;
else if(event.getKeyChar() == 'w')
charY-=5;
else if(event.getKeyChar() == 's')
charY+=5;
if(charX > 485)
charX-=6;
else if(charX < 10)
charX+=6;
if(charY > 485)
charY-=6;
else if(charY < 30)
charY+=6;
repaint();
}
public void keyPressed(KeyEvent event)
{
}
public void keyReleased(KeyEvent event)
{
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(charX, charY, 10, 10);
}
public static void main(String args[])
{
Frame frm = new Game();
frm.setVisible(true);
frm.repaint();
}
}
At school I use a Mac and at home I use a PC with Windows 10 on it. On the Mac this code tends to act different from the Windows version. In the Mac version things go as expected with the character (square) only moving a bit with each key press. On Windows however, if you press any direction (like d) the character will continue moving right even though it should only have been called once. Not only that but the frame constantly flickers when painting as well. So I was wondering why there was a difference between the versions between Mac and Windows and how I might go about fixing the flicker issue on Windows. I plan on adding in the keyPressed and keyReleased methods later so I don't think I'll have a bad time with that.
Upvotes: 3
Views: 285
Reputation: 5496
Key events differ between operating systems. Windows may rapidly create typed events when a key is down when Mac OS may create just one.
The solution is to use key bindings instead of key events, although you may have some luck finding a combination of keyPressed
and keyReleased
that work for both operating systems (would still suggest to just use key bindings).
Upvotes: 5