簡體   English   中英

GridBagLayout沒有得到預期的結果

[英]GridBagLayout not getting expected result

試圖了解GridBagLayout for Java的工作原理。 以前從未使用過它,所以它可能是我犯的一個愚蠢的錯誤。

我的目標是將JLabel放在頁面的頂部中心。 我一直在使用Oracle上的Java教程,但是沒有運氣。 標簽似乎仍在頁面的中心。 (中心位於x和y圖的死點)。

據我了解,如果將gridxgridy約束設置為0 ,則編譯器將在程序的第一行中查找文本並將其放置在文本中。 然后,我使用PAGE START錨將文本放置在頁面的中央。 我不確定自己的防御中weightxweighty函數的作用。

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

class test
{
    public static void main (String Args [])
    {
    //frame and jpanel stuff
    JFrame processDetail = new JFrame("Enter information for processes");
    JPanel panelDetail = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    //label to add on top centre
    JLabel label = new JLabel("LOOK AT ME");

    //set size of frame and operation
    processDetail.setSize(500,500);
    processDetail.setDefaultCloseOperation(processDetail.EXIT_ON_CLOSE);

    //add the label to panel
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.PAGE_START;
    c.weightx = 0; //not sure what this does entirely
    c.gridx = 0; //first column
    c.gridy = 0; //first row
    panelDetail.add(label, c);

    processDetail.add(panelDetail);
    processDetail.setVisible(true);
    }
}

您只需要使用容器將一件事添加到GBL中,因此它將居中。 如果在JLabel下添加第二個組件,則JLabel將顯示在頂部。 例如,

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.*;

public class Test2 {
   private static void createAndShowGui() {
      JPanel mainPanel = new JPanel(new GridBagLayout());
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = 0;
      gbc.gridheight = 1;
      gbc.gridwidth = 1;
      gbc.weightx = 1.0;
      gbc.weighty = 1.0;
      gbc.fill = GridBagConstraints.BOTH;
      gbc.anchor = GridBagConstraints.PAGE_START;

      mainPanel.add(new JLabel("Look at me!", SwingConstants.CENTER), gbc);   


      gbc.gridy = 1;
      gbc.gridheight = 10;
      gbc.gridwidth = 10;

      mainPanel.add(Box.createRigidArea(new Dimension(400, 400)), gbc);

      JFrame frame = new JFrame("Test2");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

我自己,如果我希望我的JLabel位於頂部,我會使用BorderLayout。

暫無
暫無

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

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