我正在开发一个独立游戏项目,当我将项目从Windows计算机移动到我的macbook时,我遇到了图形无法显示的问题。我已经更新了我的Java版本和Eclipse,但仍然遇到了这个问题。以下是处理JFrame和Panel的两个主要文件:
MainGameLoop
package hara;
import javax.swing.JFrame;
public class MainGameLoop {
public static final String gameName = "HARA v0.0";
public static void main(String[] args) {
JFrame f = new JFrame(gameName);
f.setContentPane(new MainWindow());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
和MainWindow
package hara;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import hara.gamestate.GameStateManager;
public class MainWindow extends JPanel implements Runnable, KeyListener{
public static final int WIDTH = 320;
public static final int HEIGHT = 240;
public static double wSCALE = 4;
public static double hSCALE = 4;
private Thread thread;
private boolean running;
private int FPS = 60;
private long targetTime = 1000/FPS;
private BufferedImage image;
private Graphics2D g;
private GameStateManager gsm;
public MainWindow(){
super();
setPreferredSize(new Dimension((int)(WIDTH * wSCALE), (int)(HEIGHT * hSCALE)));
setFocusable(true);
requestFocus();
}
public void addNotify(){
super.addNotify();
if(thread == null){
thread = new Thread(this);
addKeyListener(this);
thread.start();
}
}
public void init(){
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
g = (Graphics2D) image.getGraphics();
running = true;
gsm = new GameStateManager();
gsm.setState(gsm.MENUSTATE);
}
public void run(){
init();
long start;
long elapsed;
long wait;
while(running){
start = System.nanoTime();
update();
draw();
drawToScreen();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if(wait < 0){
wait = 5;
}
try {
Thread.sleep(wait);
}catch(Exception e){
e.printStackTrace();
}
}
}
private void update(){
gsm.update();
}
private void draw(){
gsm.draw(g);
}
private void drawToScreen(){
Graphics g2 = getGraphics();
g2.drawImage(image, 0, 0, (int) (WIDTH * wSCALE), (int) (HEIGHT * hSCALE), null);
g2.dispose();
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent key) {
gsm.keyPressed(key.getKeyCode());
}
public void keyReleased(KeyEvent key) {
gsm.keyReleased(key.getKeyCode());
}
}
它在我的电脑上完美运行并且绘图没有问题,但是一旦我将文件移动到我的Macbook,它就会打开一个空白的JFrame而什么都不做。我进行了测试,看看这些方法是否被正确调用了。调用绘制方法,键盘输入有效,但没有显示任何内容。如果我将窗口设置为可调整大小,并且我调整了大小,我可以非常简单地看到图形工作。我尝试了很多解决方案,但没有一个能够解决问题。我已经在这个网站上查看了很多问题,似乎没有什么对我有用。会喜欢任何想法。谢谢!
答案 0 :(得分:1)
不要使用getGraphics()来绘画。
相反,自定义绘制是通过覆盖paintComponent()
的{{1}}方法完成的。阅读Custom Painting上Swing教程中的部分,了解更多信息和工作示例。
如果要重新绘制组件,因为面板的属性发生更改,则在面板上调用repaint()。所以摆脱你的update()方法,只需调用repaint()来绘制面板。