【发布时间】:2021-06-04 22:49:57
【问题描述】:
在创建作为图像的自定义 JButton 时遇到问题。我可以使用普通的 JButton 进行所有操作(例如在第 2 行的评论中),这样我就不必获取 InputStream 并启动带有图标的按钮。 我遇到的麻烦是,当我按下重播按钮(再次播放)时,窗口关闭并且只弹出一个窗口(就像“正常”JButton 一样),但在这种情况下,4-5 个窗口重新打开并我不知道为什么。
我开始认为这是因为获得InputStream 并执行ImageIO.read() 的时间会开始游戏并看到变量 running 为假,然后开始重新打开窗口直到它为真,但我不知道如何验证一下。
注意:我有一些函数可以在 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();
}
}
【问题讨论】:
-
一个minimal reproducible example 代码帖子对我们(以及相应地对您)比完整程序(太大)或不可编译/不可运行的代码 sn-ps(你现在发布)。请考虑在您的问题中创建和发布一个。旁注通常最好将当前的 GUI 重新设置为其初始状态,而不是创建和显示新的 GUI。
标签: java image swing jar jbutton