java - 将按钮放置在图像顶部

标签 java image swing jbutton jlabel

我又回来了。我想知道如何在 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 个步骤。

  1. 为包含图像的标签设置布局管理器。

  2. 将按钮添加到标签(而不是面板)。

参见Background Panel了解更多信息和示例。

编辑:

要使组件居中,最简单的方法是:

label.setLayout( new GridBagLayout() );
label.add(button, new GridBagConstraints());

关于java - 将按钮放置在图像顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24275267/

相关文章:

java - 处理java包文件夹的简单方法?

java - Spring-Boot:依赖注入(inject)取决于配置(和使用接口(interface))

java - 如何列出亚马逊 s3 中的 key ?

Javascript 多图像加载器

java - 从 JFileChooser 获取 file.properties 并在 ResourceBundle 上使用它

Java:如何在依赖注入(inject)中获取Provider中的子类

.net - 使用 itextsharp 添加图像并跨越多个页面

java - 如何在java中制作缩略图的分页列表/目录?

JAVA 绘制线与组件

java - 如何在java中更新txt文件