I need to make an animation with a part controlled with arrows. I created JPanel which draws the "background" simply with timer and repaint(). Then I'm trying to add a canvas with key listener.
public class MyPanel extends JPanel implements ActionListener{
MyPanel(){
... creating other objects ...
MyCanvas canv = new MyCanvas();
this.add(canv);
Timer timer = new Timer(30, this);
}
...actionPerformed and other functions for background animation...
}
public class MyCanvas extends Canvas implements ActionListener, KeyListener{
int rX;
int rY;
Color color;
KeyEvent e;
int code;
Timer timer;
MyCanvas() {
rX = 400;
rY = 400;
color=Color.red;
this.setSize(1220, 840);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(5, this);
timer.start();
}
public void KeyPressed(KeyEvent e){
code = e.getKeyCode();
}
public void paint (Graphics g)
{
g.setColor(color);
g.fillOval(this.rX, this.rY, 30, 30);
}
public void actionPerformed(KeyEvent evt) {
int keyCode = evt.getKeyCode();
if(keyCode == KeyEvent.VK_LEFT){
rX-=2;
}
...and so on...
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {
repaint();
}
}
The background animation works and moves just fine, but canvas is added to JPanel, it completely covers it up. Also the key control doesn't work at all. How to fix it?