【发布时间】:2013-12-14 20:41:24
【问题描述】:
我已经开始创建一个简单的 java 游戏,现在我创建了一个带有屏幕和基本 Player 类的游戏窗口。尽管程序没有给我任何错误,但播放器图像不会绘制到屏幕上,所以我不确定从哪里开始调试问题也许有人可以帮助我?
以下是课程:
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class GameWindow extends JFrame {
public static int windowWidth = 600;
public static int windowHeight = 600;
public static void main(String[] args) {
new GameWindow();
}
public GameWindow() {
this.setSize(windowWidth, windowHeight);
this.setTitle("Berzerk Clone");
this.setVisible(true);
// Defaults the window to be set in the middle of the screen
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GameDrawing drawGame = new GameDrawing();
this.add(drawGame, BorderLayout.CENTER);
}
}
绘图类:
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class GameDrawing extends JComponent {
PlayerHuman p;
public GameDrawing() {
p = new PlayerHuman(300, 300);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D graphics = (Graphics2D)g;
graphics.setColor(Color.BLACK);
graphics.fillRect(0, 0, GameWindow.windowWidth,GameWindow.windowHeight);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.drawImage(p.getPlayerImage(), 300, 300, null);
}
}
播放器类:
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public class PlayerHuman extends GlobalPosition {
BufferedImage basicPlayer;
public PlayerHuman(int x, int y) {
super(x, y);
try {
basicPlayer = ImageIO.read(new File("Images/Player.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void draw(Graphics2D g2d) {
g2d.drawImage(getPlayerImage(), x, y, null);
}
public BufferedImage getPlayerImage() {
return basicPlayer;
}
}
感谢所有帮助。
编辑:
我的道歉
GlobalPosition 类给玩家一个起点:
public class GlobalPosition {
public int x;
public int y;
public GlobalPosition() {
x = y = 0;
}
public GlobalPosition(int _x, int _y) {
x = _x;
y = _y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int newX) {
x = newX;
}
public void setY(int newY) {
y = newY;
}
}
我有一个重绘的游戏循环类:
public class GameLoop implements Runnable {
GameWindow gWindow;
public GameLoop(GameWindow newGWindow) {
this.gWindow = newGWindow;
}
@Override
public void run() {
gWindow.repaint();
}
}
【问题讨论】:
-
这段代码无法为我编译...
GlobalPosition是什么? -
从小处着手:测试一个非常小的程序,它只加载图像,将其放入 ImageIcon 并在 JOptionPane 中显示 ImageIcon。首先解决这个问题,并且只有然后才能在更大的应用程序中使用它。此外,您最好通过
getClass().getResource("....")将图像作为 URL 读取,而不是作为文件读取。 -
我猜你需要
repaint(),但由于找不到GlobalPosition,我无法编译。 -
@mathguy54:他需要首先确保他正在寻找图像的正确位置。再次,从小处着手。
-
另外,在添加所有组件之前,不要在顶级窗口上调用
setVisible(true)。
标签: java image swing awt paint