java - JFrame Java setColor 和 fillRect 保持空白?

标签 java eclipse swing jframe

为什么我在调试或运行时看到的是空白屏幕而不是黑色?我到处都看过,也做了很多尝试!请帮忙。我只是想让我的屏幕变黑,因为我是所有这些 java 编码的初学者。我不认为代码有任何问题,因为我没有收到任何错误。我正在使用 Eclipse。

package com.techon.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 JFrame frame;
private Thread thread;
private boolean running = false;

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() {
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
public void run() {
    while(running);{
        update();
        render();
}
}
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();
}
}

最佳答案

替换

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

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

由于 while(running);它没有在循环内执行其他语句。

关于java - JFrame Java setColor 和 fillRect 保持空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21366919/

相关文章:

Java 8 : No errors - Why is this for loop running forever and not showing anything?

eclipse - 插件中何时需要 Activator 类/"Bundle-Activator",何时不需要?

java - 尝试从位置 x,y 处的网格检索颜色 JPANEL

java - 如何在 Swing 中创建以下布局?

java - FutureTask 是如何进行异步计算的

java - flyway db迁移中如何排除部分数据库

java - 能够在组织导入首选项中添加分隔符/换行符 (Scala-IDE)

java - 不同组件的布局问题?

java - 如何以编程方式按名称 getBean()

java - Android 库项目 JAR