我又回来了。我想知道如何在 GUI 中的图像顶部放置一个按钮。这是我当前的代码:
private static JPanel titlePanel = new JPanel();
private static JLabel titleScreen = new JLabel();
private static JLabel titleScreenBackground = new JLabel();
private static JButton startGameButton = new JButton("START GAME");
private static ImageIcon titleScreenPic = new ImageIcon("http://icdn6.digitaltrends.com/image/battleship-650x0.jpg");
private static JFrame frame=new JFrame(); //creates frame
public static void main(String[] args) throws MalformedURLException{
titleScreen();
}
public static void titleScreen() throws IOException{
titleScreen.setLayout(new GridBagLayout());
titlePanel.setLayout(new GridBagLayout());
GridBagConstraints c1 = new GridBagConstraints();
c1.gridx = 0;
c1.gridy = 0;
c1.anchor = GridBagConstraints.PAGE_END;
titleScreenBackground.setIcon(titleScreenPic);
titlePanel.add(startGameButton);
titlePanel.setAlignmentY(SwingConstants.BOTTOM);
frame.add(titleScreenBackground);
frame.add(titlePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(630, 300); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
我尝试将面板设为 gridbaglayout,以便可以将组件放置在同一个单元格中,但它仍然首先放置图像,然后将按钮直接放置在其旁边。
编辑:我重做了代码,使其达到我想要的效果。正如您所看到的,我尝试设置按钮位置的行不会对按钮执行任何操作。
最佳答案
how I would go about placing a button on top of an image in a GUI.
如果您想将 Swing 按钮放置在图像顶部,则需要执行 2 个步骤。
为包含图像的标签设置布局管理器。
将按钮添加到标签(而不是面板)。
参见Background Panel了解更多信息和示例。
编辑:
要使组件居中,最简单的方法是:
label.setLayout( new GridBagLayout() );
label.add(button, new GridBagConstraints());
关于java - 将按钮放置在图像顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24275267/