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

时间:2013-08-28 18:58:22

标签: 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。我很难过......

1 个答案:

答案 0 :(得分:3)

如果您修复了编译错误并将代码包装到可运行的演示中,您会发现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
  }
}