簡體   English   中英

Java Swing的GridBagLayout不會將組件放置在網格單元的頂部

[英]Java Swing's GridBagLayout will not position component at the top of the grid cell

我已盡我所能將其簡化為代碼。 我已經使用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最終在屏幕中心呈正方形。 我怎樣才能到達頂部? 我看了如何使用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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM