[英]Java Swing renders a different background
我正在開發一款游戲。 我遇到的問題是在游戲渲染開始之前(應該渲染黑色背景)它顯示一個白色背景。 它會發生一秒鍾,然后開始正確的渲染。 我不確定如何解決這個問題。
所有的渲染代碼都在一個線程內運行。 我試圖在第一次渲染后使 window 可見,但我在 createImage 方法上得到了 NPE。
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame implements Runnable {
private Thread windowThread;
private int width, height;
private String windowName;
private boolean isExecuting;
private GameState gameState;
private Graphics graphics;
public Window() {
loadWindowConfiguration();
windowThread = new Thread(this);
}
private void loadWindowConfiguration() {
setWindowProperties();
}
private void setWindowProperties() {
this.windowName = Constants.WINDOW_NAME;
this.width = Constants.WINDOW_WIDTH;
this.height = Constants.WINDOW_HEIGHT;
this.setTitle(windowName);
this.setSize(new Dimension(this.width, this.height));
this.setResizable(Constants.IS_RESIZABLE_WINDOW);
this.setFocusable(Constants.IS_FOCUSABLE_WINDOW);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(Constants.IS_VISIBLE_WINDOW); // Set to true
graphics = (Graphics2D)this.getGraphics();
}
public void update(double delta) {
gameState.update(delta);
}
public void render() {
Image img = this.createImage(this.getWindowWidth(), this.getWindowHeight());
Graphics g = img.getGraphics();
Graphics2D doubleBuffer = (Graphics2D) g;
doubleBuffer.setColor(getBackground());
//doubleBuffer.fillRect(0, 0, this.getWindowWidth(), this.getWindowHeight());
gameState.render(doubleBuffer);
graphics.drawImage(img, 0, 0, this);
}
public void startWindow() { windowThread.start(); }
public void stopWindow() {
this.isExecuting = false;
}
private void clean() {
graphics.dispose();
this.dispose();
windowThread.interrupt();
}
@Override
public void run() {
this.isExecuting = true;
gameState.loadGame();
while(this.isExecuting) {
update(delta);
render();
}
clean();
}
}
您需要使用 Java AWT 中的setBackground()
方法來創建背景。
您是否使用 Eclipse 來構建您的應用程序? 如果是這樣,只需使用 WindowBuilder,如果您在渲染背景時遇到問題,所有內容都應該在側工具欄上。
正如 WJS 建議的那樣,我建議您閱讀 Java Swing 的文檔。 您的大部分問題應該可以在此鏈接中得到解答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.