我正在尝试制作一个乒乓球游戏,但每次我尝试启动它来测试缓冲策略时,它会立即关闭。我尝试通过添加启动和停止同步void来解决这个问题,但它似乎没有用。通常这种事情很容易修复,但我感到很困惑。
package pong;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
JFrame frame; //game window stuff
public final int WIDTH = 400;
public final int HEIGHT = WIDTH / 16 * 9;
public final Dimension gameSize = new Dimension(WIDTH, HEIGHT);
public final String TITLE = "Pong InDev";
BufferedImage Image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
static boolean gameRunning = false; //Is game running?
public void run() {
while (gameRunning) {
tick();
render();
}
}
//attempted to fix problem
public synchronized void start1() {
gameRunning = true;
new Thread(this).start();
System.exit(0);
//End start method
}
public static synchronized void stop() {
gameRunning = false;
//End stop method
}
public Game() {
frame = new JFrame();
setPreferredSize(gameSize);
setMinimumSize(gameSize);
setMaximumSize(gameSize);
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
frame.setTitle(TITLE);
frame.setLocationRelativeTo(null);
frame.setLayout(new BorderLayout());
}
public void tick() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(Image, 0, 0, getWidth(), getHeight(), null);
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.start1();
}
}
答案 0 :(得分:2)
System.exit(0)
看起来像是罪魁祸首。尝试删除它。