【问题标题】:Why Won't the Screen Change Color?为什么屏幕不变色?
【发布时间】:2014-01-09 20:23:55
【问题描述】:

我一直在尝试修复,但它永远不会改变屏幕。我正在尝试使用 render() 方法中看到的图形。告诉我渲染方法内部是否有问题,以便我可以放松,因为我似乎找不到问题。

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

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

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

public synchronized void stop() {
    running = false;
    try{
        thread.join();
    }catch(InterruptedException e) {
        e.printStackTrace();
    }
}

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

    frame = new JFrame();
}

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

void tick() {}

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());
    bs.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();
}

}

【问题讨论】:

  • 在显示()之前,您正在处理()您的 BufferStrategy。这可不好。
  • 我试过了。好像没用。
  • 您的代码似乎与this question 非常相似。我会尝试将您的代码与该代码进行比较,因为我认为他们可能使用相同的教程。
  • 某些组件需要将 opaque 属性设置为 true。请问可以试试这个吗?

标签: java swing graphics jframe awt


【解决方案1】:

让我给你一个错误的堆栈跟踪。

这里甚至没有调用您的渲染方法。
这是因为您的 run 方法根本没有被调用。
这一切背后的原因是您在创建 Thread 时没有传递正确的 Runnable 对象。它创建一个空运行的线程。
在您的启动方法中,只需替换

thread = new Thread();

thread = new Thread(this);

它应该可以工作。

希望这可以帮助。享受吧。

【讨论】:

    猜你喜欢
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 2011-10-10
    相关资源
    最近更新 更多