This post continues a serie of posts I’m writing about 2D game development in Java.
A simple example of an JPanel that implements KeyListener (and a little trick) to handle KeyEvents to move a white square.
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JPanel; import javax.swing.JTextField; public class KeyPanel extends JPanel implements KeyListener{ private int x=50,y=50; public KeyPanel() { JTextField textfield = new JTextField(); textfield.addKeyListener(this); add(textfield); textfield.setPreferredSize(new Dimension(0,0)); } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) x-=5; if (e.getKeyCode() == KeyEvent.VK_RIGHT) x+=5; if (e.getKeyCode() == KeyEvent.VK_DOWN) y+=5; if (e.getKeyCode() == KeyEvent.VK_UP) y-=5; this.repaint(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); g.fillRect(0, 0, 500, 500); g.setColor(Color.white); g.fillRect(x, y, 50, 50); } } |
Download the complete NetBeans source project files: KeyTest.tar.bz2.
Be First to Comment