Reputation: 139
I have the following two classes, the main-class (SamG) and the Panll-class. I have implemented the KeyListener in the Panll-class, but it doesn't seem to work.
public class SamG {
public static void main(String[] args) {
JFrame jf = new JFrame("My APP");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(800, 400);
jf.setVisible(true);
jf.pack();
jf.setContentPane(new Panll());
}
}
public class Panll extends JPanel implements KeyListener {
int x=100,y=100;
boolean run=true;
Panll() {
addKeyListener(this);
}
@Override
public void paint (Graphics g) {
super.repaint();
g.clearRect(0, 0, 800, 400);
update();
draw(g);
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
Logger.getLogger(Panll.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void update(){
x++;
y++;
}
public void draw(Graphics g){
g.drawOval(x, y, 100, 100);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar());
}
@Override
public void keyReleased(KeyEvent e) {
}
}
Upvotes: 0
Views: 458
Reputation: 4039
First never send main thread to sleep. Create a new Thread that periodically calls a repaint of your panel.
Second don't use paint()
method to draw your stuff. Use the paintComponent()
method instead.
Third add your KeyListener
to your JFrame
. Your JPanel
won't receive the KeyEvents
because it never gets the Focus.
Upvotes: 1
Reputation: 6435
you can't focus a JPanel without explicit allowing it with setFocusable(true);
. if you add this line you can take you focus on the JPanel. if you then press any button the KeyListener works just fine
Upvotes: 1