JFrame 立即关闭

3

我正在尝试制作一个乒乓球游戏,但每次我试图启动它来测试缓冲策略时,它立即关闭。我尝试通过添加start和stop同步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();
}
}
1个回答

2
在start方法的结尾处使用System.exit(0)看起来是罪魁祸首。尝试将其删除。

是的,start1 方法结束了。我想就这样。 - Alvin Bunk
谢谢,当涉及Java时我是一个巨大的新手。 - Max Fischer
没问题 - 我数不清有多少次仅仅是让别人看一眼我的代码就节省了大量时间来追踪错误。 - ash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接