gpt4 book ai didi

Java BorderLayout 无法正确调整大小/居中?

转载 作者:行者123 更新时间:2023-12-01 13:02:16 26 4
gpt4 key购买 nike

我知道这里有一些非常简单的事情我做错了,但我就是看不到它。我尝试过在线搜索并检查其他答案,但找不到遇到相同问题的人。

我正在尝试创建一个 JFrame,其中包含北部的按钮面板和南部的按钮面板,并让用户加载图像以进入中心。当用户调整 JFrame 大小时,我希望中心的图像保持水平和垂直居中,但图像仅保持水平居中。我正在使用 JLabel 来保存图像。你能帮我指出正确的方向吗?

theJFrame.setResizable(true);

imageLabel.setIcon(new ImageIcon(theImage));
imagePanel.add(imageLabel);
theJFrame.add(imagePanel, BorderLayout.CENTER);

theJFrame.pack();

编辑:用户 Hovercraft Full of Eels 发布了一个有效的解决方案,该解决方案已被删除,因此我无法选择它,但他们建议将 imageLabel 设置为具有 GridBagLayout。我进行了更改,现在它保持垂直和水平居中。

编辑:我很难为 SSCCE 削减足够的代码,因为我有另一个类创建并调用 GUI 类来运行它,但我可以为您提供更详细的代码示例:

    theJFrame = new JFrame();
theFilterButtonPanel = new JPanel();
theUtilityButtonPanel = new JPanel();
imageLabel = new JLabel();

theJFrame.setResizable(true);
theJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and add filter buttons
for (final Filter f : MY_FILTERS) {
createFilterButton(f.getDescription());
}

theJFrame.add(theFilterButtonPanel, BorderLayout.NORTH);
myUtilityButtonPanel.add(createCloseButton());
theJFrame.add(theUtilityButtonPanel, BorderLayout.SOUTH);
theJFrame.add(imageLabel, BorderLayout.CENTER);

当我这样做时,只需将 imageLabel 直接添加到 JFrame 中,它就会将其放在窗口的最左侧,如果我调整它的大小,它会保持垂直居中。如果我使用

    JPanel theImagePanel = new JPanel();
theImagePanel.add(imageLabel);
theJFrame.add(theImagePanel, BorderLayout.CENTER);

然后它会使其水平居中,但在调整窗口大小时它会保持在屏幕顶部(不会使其垂直居中)。

最佳答案

将 JLabel 直接添加到框架中。无需先将图像添加到面板。

仅图像 JLabel 的默认对齐方式是在可用空间中垂直和水平居中。

关于Java BorderLayout 无法正确调整大小/居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23437078/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com