java - Java Swing 呈现不同的背景
问题描述
我正在开发一款游戏。我遇到的问题是在游戏渲染开始之前(应该渲染黑色背景)它显示一个白色背景。它会发生一秒钟,然后开始正确的渲染。我不确定如何解决这个问题。
所有的渲染代码都在一个线程内运行。我试图在第一次渲染后使窗口可见,但我在 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();
}
}
解决方案
您需要使用setBackground()
Java AWT 中的方法来创建背景。
您是否使用 Eclipse 来构建您的应用程序?如果是这样,只需使用 WindowBuilder,如果您在渲染背景时遇到问题,所有内容都应该在侧工具栏上。
正如 WJS 所建议的,我建议您阅读 Java Swing 的文档。您的大部分问题应该可以在此链接中得到解答。
推荐阅读
- reactjs - 如何在 Link 和 Route 组件中同时传递 props?
- html - 有人知道为什么 font-weight: bold; 不能在移动设备上工作?
- javascript - 来自另一个模块的 Jest 模拟函数:结果值未定义
- html - 使 objectheader 具有粘性并使页面的其余部分可滚动
- java - Android OpenCV 相机示例只是显示黑屏
- javascript - Chrome 在 html 文档中找不到 Javascript 函数
- mysql - WHERE P=BN.. AS B 和 WHERE P=N 有什么区别?
- java - 尝试向我的 Hashmap 添加一个实例方法,该方法采用两个参数表示一个键和一个值
- java - 如何避免getter和setter springboot实体?
- java - 正则表达式拆分字符串,遵循 ABNF 形式