Hello,
I am unable to register the right key event from this program. Besides setting the focus of JPanel to the KeyListener, I am not sure what else can be done. I will be grateful for any help.
Thank you!
import java.awt.*;
import java.awt.event.KeyListener;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel
{
private int x = 20, y = 20;
private boolean flag = true;
public Board()
{
setFocusable(true);
addKeyListener(
new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_RIGHT )
{
flag = false;
repaint();
}
}
}
);
}
public void paintComponent(Graphics g)
{
if (flag)
{
g.setColor (Color.BLUE);
g.fillRect (x + 10, y, 20, 20);
}
else
{
g.setColor (Color.RED);
g.fillRect (x + 100, y, 20, 20);
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
Board test = new Board();
test.requestFocus();
f.add(test);
f.setSize(600,600);
f.setVisible(true);
}
}