首页 > 解决方案 > 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();
    }
}

标签: javaswinggraphicsawtrendering

解决方案


您需要使用setBackground()Java AWT 中的方法来创建背景。

您是否使用 Eclipse 来构建您的应用程序?如果是这样,只需使用 WindowBuilder,如果您在渲染背景时遇到问题,所有内容都应该在侧工具栏上。

正如 WJS 所建议的,我建议您阅读 Java Swing 的文档。您的大部分问题应该可以在此链接中得到解答。


推荐阅读