Boa noite galera,
Sou novato e gostaria da ajuda de vocês.
Meu objetivo é colocar um imagem num panel e move-la com as setas do teclado, mas não estou conseguindo. Segue o código:
[code]
public class Board extends JPanel {
private Image ball;
private int x = 250;
private int y = 200;
public boolean down;
public boolean up;
public boolean right;
public boolean left;
Board() {
addKeyListener(new TAdapter());
ImageIcon b = new ImageIcon(this.getClass().getResource("lixo.png"));
ball = b.getImage();
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(ball, x, y, this);
}
public void move() {
if (left) {
x -= 5;
}
if (right) {
x += 5;
}
if (up) {
y -= 5;
}
if (down) {
y += 5;
}
}
public static void start() {
JFrame f = new JFrame();
f.add(new Board());
f.setVisible(true);
f.setSize(500, 500);
}
public void actionPerformed(ActionEvent e) {
move();
repaint();
}
private class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
left = true;
up = false;
down = false;
}
if (key == KeyEvent.VK_RIGHT) {
right = true;
up = false;
down = false;
}
if (key == KeyEvent.VK_UP) {
up = true;
right = false;
left = false;
}
if (key == KeyEvent.VK_DOWN) {
down = true;
right = false;
left = false;
}
}
}
public static void main(String[] args) {
start();
}
}[/code]