【问题标题】:BorderLayout.CENTER doesn't center my JPanelBorderLayout.CENTER 没有使我的 JPanel 居中
【发布时间】:2014-05-11 02:11:32
【问题描述】:

我有以下代码来创建我的 GUI。

private static void createGUI() {
  JFrame frame = new JFrame ("Tiles Game");
  frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

  frame.setJMenuBar (new JMenuBar());
  frame.setContentPane (MainPanel.getInstance());

  frame.pack();
  frame.setResizable (false);
  frame.setLocationRelativeTo (null);
  frame.setVisible (true);
}

这是 MainPanel(扩展 JPanel)构造函数:

private MainPanel() {
  super (new BorderLayout());
  setPreferredSize (new Dimension (IMG_SIZE + 10, IMG_SIZE + 10));
  ...
  panel = new ImagePanel();
  add (panel, BorderLayout.CENTER);
}

这是 ImagePanel(扩展 JPanel)构造函数:

private ImagePanel() {
  super();
  setPreferredSize (new Dimension (IMG_SIZE, IMG_SIZE));
  ...
}

但是 ImagePanel 与 MainPanel 的左上角对齐而不是居中,所以我在底部和右侧得到了一堆额外的填充,而在顶部和左侧没有。如何将它放在 MainPanel 的中心?

【问题讨论】:

  • 这可能是你的形象。图像具有固定大小,如果设置为 0、0 坐标,则每次调整 JFrame 大小时,您的面板看起来都没有居中。
  • 如果您在对齐方面遇到问题并且不确定它会导致哪个组件,请尝试为您的组件设置一些可见的边框。例如,将 this.setBorder(new EtchedBorder()); 放入您的 MainPanel 构造函数中。然后,您将看到初始化时所需的界限。至于您的代码,我认为布局没有问题 - 一定是其他问题。

标签: java swing jpanel center


【解决方案1】:

可能发生的事情是您正在从左上角的(0, 0) 绘制图像。然后将首选尺寸设置为大 10 像素,这会使面板变大,但图像仍为 (0, 0)

改为使用相同大小但不加 10,而只需为面板使用 EmptyBorder。同样作为建议,覆盖getPreferredSize() 而不是使用setPreferredSize()

public class ImagePanel extends JPanel {
    public ImagePanel() {
        setBorder(new EmptyBorder(10, 10, 10, 10));
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(IMG_SIZE, IMG_SIZE);
    }
}

如果容器要大于子面板,您可能还需要考虑为容器面板使用GridBagLayout,以确保居中。你能做的事情很少。甚至考虑使用ImageIconJLabel 而不是绘画(如果不需要调整图像大小(如Camickr(+1) 所指出的那样)。只需设置JLabel标签的布局并将其设置为框架的内容窗格。

ImageIcon icon = new ImageIcon(...)
JLabel frameBackground = new JLabel(icon);
frameBackground.setLayout(new BorderLayout());
frame.setContentPane(frameBackground);

【讨论】:

  • 所以问题是 BorderLayout 不尊重首选尺寸(甚至最大尺寸),只是调整了 ImagePanel 的大小以适应 MainPanel。使用 GridBagLayout 将我的 ImagePanel 正确居中。
【解决方案2】:

不要使用 JPanel 来显示图像。

改为使用JLabelImageIcon

如果您希望图像周围有额外的空间,则可以在标签上使用EmptyBorder

【讨论】:

  • 我不能使用 ImageIcon,因为我也在里面做一些图像处理。使用 JLabel 而不是 JPanel 有什么特别的原因吗?
猜你喜欢
  • 2020-08-03
  • 2011-09-18
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多