创建自定义JButton为Image时遇到问题。我用一个普通的JButton(就像在第二行评论中一样)工作,这样我就不必获得一个InputStream并启动按钮有一个图标。我遇到的问题是,当我按下重播按钮(再次播放)时,窗口关闭,只有一个窗口应该弹出(因为它发生在"正常"但在这种情况下,4-5个窗口重新打开,我不知道为什么。
我开始认为这是因为时间得到一个InputStream
和做ImageIO.read()
游戏会开始,看到变量运行是假的,然后开始重新打开窗口,直到它是真的,但我看不出如何验证。
注意:我在ActionPerformed上设置了一些函数来验证蛇是否发生碰撞,如果发生碰撞,running = false
和GameOver()
将被调用
public class GamePanel extends JPanel implements ActionListener {
JButton replay; //= new JButton("Play Again");
GamePanel() {
...
try {
InputStream is_replay = this.getClass().getResourceAsStream("/Snake/lib/img/playagain.png");
ImageIcon icon = new ImageIcon(ImageIO.read(is_replay));
replay = new JButton(icon);
replay.setBorder(BorderFactory.createEmptyBorder());
replay.setContentAreaFilled(false);
...
} catch (IOException|FontFormatException e) {
e.printStackTrace();
}
this.add(replay);
replay.setVisible(false);
replay.setBounds(SCREEN_WIDTH/2 - 100, SCREEN_HEIGHT - 200, 200, 100);
...
startGame();
}
public void startGame() {
spawnApple();
running = true;
timer = new Timer(DELAY, this);
timer.start();
}
public void gameOver(Graphics g) {
...
replay.setVisible(true);
replay.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == replay) {
JComponent comp = (JComponent)e.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
win.dispose(); //It will close the current window
new GameFrame(); //It will create a new game
}
}
});
}
}
public class GameFrame extends JFrame {
GameFrame() {
JPanel panel = new GamePanel();
this.add(panel);
panel.setLayout(null); //Needed to add components
this.setTitle("Snake Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack(); //Fit JFrame to the components
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
public class SnakeGame {
public static void main(String[] args) throws Exception {
new GameFrame();
}
}
"在这种情况下,4-5 Windows重新打开">
这表明你可能在重放JButton中添加了多个actionlistener。每次调用game over方法时都会添加一个新的监听器,这是不正确的。我不会将ActionListener添加到game over方法中的按钮中,而是在创建重播按钮的位置添加它。