【发布时间】:2015-05-09 23:50:05
【问题描述】:
我对java很陌生。非常。就像我今天基本上开始一样。我以前有其他语言的编程知识,如 c、c++、PHP、javascript 等,但我无法弄清楚这一点。我开始在 Youtube 上观看有关如何用 Java 制作视频游戏的教程(来自 theChernoProject 的视频),但在大约 7 集里,我遇到了一个问题,我们有窗口,我们在整个东西上画了一个黑色矩形,该应用程序冻结了我的整个计算机。这是我的代码:
package com.darksun.theonetruemike.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 Thread thread;
private JFrame frame;
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();
}
}
我正在使用 eclipse 来制作这个项目(非常违背我的意愿),当我按下 Debug 按钮时,会出现窗口,并且我的计算机死机,导致不得不强制退出整个计算机。如果可以,请提供帮助,并提前感谢您的帮助!
【问题讨论】:
-
你怎么知道它冻结了,它似乎什么也没做。还。您的主循环可能会超支,这可能会消耗您的 CPU 周期...
-
我知道它死机了,因为我按下了关闭按钮,大约需要 5 分钟什么都不做,然后我不得不强制退出我的电脑
-
你想用线程完成什么?
-
类似 Thread.sleep(16);在你调用渲染之后
-
当我运行这个渲染时,每秒被调用 7500 次,这有点过分了。