我几周前开始编码,目前正在尝试使用 Swing 和 AWT 为游戏创建 Java GUI。我创建了下面的代码。
public class UI {
JFrame frame = new JFrame();
JPanel backgroundPanel;
JLayeredPane buttonPanel;
JButton play = new JButton("Play!");
JLabel background;
public UI() {
backgroundPanel = new JPanel(new BorderLayout());
ImageIcon imgBackground = new ImageIcon(this.getClass().getResource("/img/connect4_4.png"));
background = new JLabel("", imgBackground, JLabel.CENTER);
backgroundPanel.add(background, BorderLayout.CENTER);
backgroundPanel.add(play, BorderLayout.NORTH);
frame.add(backgroundPanel);
frame.setTitle("Connect 4");
frame.setSize(450, 450);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
使用此代码,我创建了一个带有背景图像的面板,并在屏幕顶部有一个播放按钮。然而,我想做的是将播放按钮居中放置在图像的中心,并且它不采用全屏尺寸,而仅采用固定尺寸(可能是 50x50 像素)。我该怎么做?
拥有 JLayeredPane 字段,您就走在正确的轨道上。但您的代码当前没有使用它。
您需要为 JLayeredPane 提供一个 OverlayLayout。大多数其他布局不会定义组件相互重叠时的行为。
将背景组件和按钮都放置在该 JLayeredPane 中,然后仅将 JLayeredPane 添加到框架中:
backgroundPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
backgroundPanel.setAlignmentY(Component.CENTER_ALIGNMENT);
play.setAlignmentX(Component.CENTER_ALIGNMENT);
play.setAlignmentY(Component.CENTER_ALIGNMENT);
buttonPanel = new JLayeredPane();
buttonPanel.setLayout(new OverlayLayout(buttonPanel));
buttonPanel.setLayer(backgroundPanel, JLayeredPane.DEFAULT_LAYER);
buttonPanel.setLayer(play, JLayeredPane.PALETTE_LAYER);
buttonPanel.add(backgroundPanel);
buttonPanel.add(play);
// ...
frame.getContentPane().add(buttonPanel);