Java Swing 的 GridBagLayout 不会将组件定位在网格单元的顶部

标签 java swing layout user-interface gridbaglayout

我已经尝试在代码中尽可能地简化它。我已经使用 GridBagLayout 很长时间了,由于某种原因我从未遇到过这种情况。

JDialog dialog = new JDialog();
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setResizeable(true);

JPanel guiHolder = new JPanel();
guiHolder.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
guiHolder.add(new JLabel("my test"), gbc);

dialog.add(guiHolder);
dialog.setSize(new Dimension(320, 240);
dialog.setSize(true);

JLabel 最终在屏幕中央呈正方形。我怎样才能让它到达顶部?我看过How To Use GridBagLayout 。我被难住了...

最佳答案

如果您修复了编译错误并将代码包装到可运行的演示中,您会看到 GridBagLayout 的工作方式如广告所示:

import java.awt.*;
import javax.swing.*;

public class Test implements Runnable
{
  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new Test());
  }

  public void run()
  {
    JDialog dialog = new JDialog();
    dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    dialog.setResizable(true);  // fixed mispelling here

    JPanel guiHolder = new JPanel();
    guiHolder.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.PAGE_START;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    guiHolder.add(new JLabel("my test"), gbc);

    dialog.add(guiHolder);
    dialog.setSize(new Dimension(320, 240));
    dialog.setVisible(true);  // fixed wrong method name here
  }
}

关于Java Swing 的 GridBagLayout 不会将组件定位在网格单元的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18496086/

相关文章:

java - 使用自定义高度在 Canvas 上绘制文本 - Android

java - 在具有相同 CN 名称但别名不同的信任库中导入多个 CA

java - 从插件调用代码时出现问题 : "org.eclipse.jface" - Export Deployable Eclipse plug-in

java - 临时更改 JButton 背景颜色?

android - 相对布局在不同的模拟器中搞砸了

java - Appcompat_v7 -->res -->layout error - Orientation Lint 错误

java - 尝试分割长字符串并将其数据用于列表

Java JList和列表问题

wpf - WPF 布局面板(例如网格)的过度嵌套在计算上是否昂贵?

java - "Abstraction in Java."的正确定义是