我是新來的Java,我正在嘗試做一個有趣的簡單遊戲。 我第一次試圖把重繪到paintComponent(),它的工作,直到我試圖添加一些背景。 有沒有人知道如何讓我的球員有或沒有'重繪'移動?玩家精靈不會在Java 2D遊戲中移動(重繪)
Screen類
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Frame extends JFrame implements KeyListener
{
Map map;
public static void main(String[] args)
{
Frame frame = new Frame();
frame.addKeyListener(new Frame());
frame.setVisible(true);
}
public Frame()
{
setInit();
}
private void setInit()
{
map = new Map();
add(map);
setSize(800, 800);//frame size 300 width and 300 height
setTitle("Eerste Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setLayout(new GridLayout(1,1,0,0));
setFocusable(true);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
map.movePlayer(keyCode);
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
地圖類
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
class Map extends JPanel
{
Player player;
BufferedImage map;
public Map() {
player = new Player();
try{map = ImageIO.read(new File("img/map.png"));}catch (Exception e){};
}
public void movePlayer(int keyPressed)
{
player.move(keyPressed);
revalidate();
repaint();
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(player.img,player.getX(),player.getY(), null);
}
}
Player類
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
class Player
{
BufferedImage img = null;
private int x = 100;
private int y = 100;
public Player()
{
try{img = ImageIO.read(new File("img/bob.png"));}catch (Exception e){}
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void move(int keyPressed)
{
if(keyPressed == KeyEvent.VK_W) {
// handle up
y = y - 5;
}
if (keyPressed == KeyEvent.VK_A) {
// handle links
x = x - 5;
}
if (keyPressed == KeyEvent.VK_S) {
// handle onder
y = y + 5;
}
if (keyPressed == KeyEvent.VK_D) {
// handle right
x = x + 5;
}
}
}
WOW,非常感謝! 這很明顯,如果你知道這個問題。 XD 感謝您的提示,我會改變exeption。 – SynthWeaver