我想要一個簡單的精靈在我的屏幕上移動。我無法理解這段代碼出了什麼問題,因爲我遵循了不同源代碼的指示,但刪除了其他代碼中其他功能添加的一些複雜性。 現在我只是想讓它在屏幕上自由移動。 後來我打算讓動畫在移動時改變。 這兩個類的代碼如下。雪碧不能移動JPanel
package game;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer:
public class Game extends JPanel implements ActionListener {
int x, y, b_width, b_height;
Player player;
Timer timer;
public Game() {
addKeyListener(new KeyRecorder());
player = new Player();
timer = new Timer(5, this);
timer.start();
}
public void paint(Graphics g){
g.drawImage(player.image, player.getX(), player.getY(), this);
}
@Override
public void actionPerformed(ActionEvent e) {
player.move();
repaint();
}
public class KeyRecorder extends KeyAdapter{
public void keyPressed(KeyEvent e){
player.keyPressed(e);
repaint();
}
public void keyReleased(KeyEvent e){
player.keyReleased(e);
}
}
}
以及sprite:
package game;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Player {
private String sprite = "sprite.png";
int x, y, dx, dy;
int width, height;
Image image;
public Player() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(sprite));
image = ii.getImage();
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void move() {
x = x + dx;
y = y + dy;
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP){
dy -= 3;
}
if(key == KeyEvent.VK_DOWN){
dy += 3;
}
if(key == KeyEvent.VK_LEFT){
dx -= 3;
}
if(key == KeyEvent.VK_RIGHT){
dx += 3;
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP){
dy -= 0;
}
if(key == KeyEvent.VK_DOWN){
dy += 0;
}
if(key == KeyEvent.VK_LEFT){
dx -= 0;
}
if(key == KeyEvent.VK_RIGHT){
dx += 0;
}
}
}
所以,我們很清楚,是否應該將paint()方法更改爲「@Override paintComponent(Graphics g){}」?如果是這樣,它不起作用。我也在構造函數中添加了setFocusable – 2013-02-18 16:49:27
這不會解決您的問題,但是您重寫了錯誤的方法! paintComponent()是你應該添加自定義繪畫邏輯的地方。你還應該在頂部有一個super.paintComponent()。 – camickr 2013-02-18 20:27:41