我正在使用Java swing创建游戏,并且在使用BoxLayout的“ Game Over”屏幕的设计中出现了问题。
因此,我已将两个JLabel与简单消息垂直对齐,并且尝试在下面添加另一个“再次播放” JButton。 (在JFrame级别的顶部,我正在使用BorderLayout。)
我使用加载的ImageIcon(大于默认尺寸)自定义了JButton,但屏幕显示为以下屏幕截图:
我的实现有什么问题?如下:
//initialize the game over screen
JPanel overPanel = new GameOverScreen();
overPanel.setLayout(new BoxLayout(overPanel, BoxLayout.Y_AXIS));
JLabel message = new JLabel("Game Over!");
JLabel finalScore = new JLabel("Score: " + game.getScore());
//Play again button
JButton again = new JButton(new ImageIcon("files/again.jpg"));
again.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame();
}
});
again.setPreferredSize(new Dimension(450, 100));
again.setMargin(new Insets(0, 0, 0, 0));
again.setBorder(null);
//manage center alignments and add to JPanel
message.setAlignmentX(Component.CENTER_ALIGNMENT);
finalScore.setAlignmentX(Component.CENTER_ALIGNMENT);
overPanel.add(Box.createVerticalStrut(250)); //invisible spacers
overPanel.add(message);
overPanel.add(finalScore);
overPanel.add(Box.createVerticalStrut(50));
overPanel.add(again);
add(overPanel, BorderLayout.CENTER); //this is in a JFrame extended class