【问题标题】:Java - Won't display a black screenJava - 不会显示黑屏
【发布时间】:2015-07-06 18:11:42
【问题描述】:

当我告诉它时,我的 Java 程序不会显示黑屏。我只能看到一个 0 FPS 的灰色窗口。

这是我的代码:

package com.none.rain;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

public class Game extends Canvas implements Runnable {
    private static final long serialVersionUID = 1L;

    public static int width = 300;
    public static int height = width / 16 * 9;
    public static int scale = 3;

    private boolean running = false;
    private JFrame frame;
    private Thread thread;

    public Game() {
        Dimension size = new Dimension(width*scale, height*scale);
        setPreferredSize(size);

        frame = new JFrame();
    }

    public synchronized void start() {
        running = true;
        thread = new Thread(this, "Display");
        thread.start();
    }

    public synchronized void stop() {

        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (running) {

        }
    }

    public void update() {

    }

    public void render() {
        BufferStrategy bs = getBufferStrategy();
        if (bs == null) {
            createBufferStrategy(3);
            return;
        }

        Graphics g = bs.getDrawGraphics();
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.dispose();
        bs.show();
    }

    public static void main(String[] args) {
        Game game = new Game();
        game.frame.setResizable(false);
        game.frame.setTitle("Rain");
        game.frame.add(game);
        game.frame.pack();
        game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        game.frame.setLocationRelativeTo(null);
        game.frame.setVisible(true);

        game.start();
    }

}

【问题讨论】:

    标签: java graphics colors


    【解决方案1】:

    让显示屏变黑是您在 render() 方法中执行的操作,但您从不调用它。

    如果我获取您的代码并在 run() 方法中添加对 render() 的调用,我会得到一个黑色背景的框架:

    public void run() {
        while (running) {
            render();
        }
    }
    

    【讨论】:

    • 哦,完全忘记添加了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2012-01-15
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多