簡體   English   中英

GridBagLayout填充

[英]GridBagLayout padding

我正在使用GridBagLayout (當前)顯示兩行。 我知道這個布局對於這個任務來說太過分了,但我正在努力學習如何使用它。 問題是我已將兩個面板添加到兩個單獨的行中,並且內容周圍存在巨大差距(請參閱下面的圖像和代碼): alt text http://www.imagechicken.com/uploads/1264533379009864500.png

Image background;
    public Table(){
        super();
        ImageIcon ii = new ImageIcon(this.getClass().getResource("pokerTableV2.png"));
        background = ii.getImage();
        setSize(Constants.FRAME_WIDTH, Constants.TABLE_HEIGHT);

        setLayout(new GridBagLayout());

        GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.fill = GridBagConstraints.HORIZONTAL;

        JButton button = new JButton("hello world");
        JPanel panel1 = new JPanel();
        panel1.setPreferredSize(new Dimension(800,100));
        panel1.add(button, BorderLayout.CENTER);
        panel1.setBackground(Color.yellow);
        add(panel1, constraints);

        constraints.gridx = 0;
        constraints.gridy = 1;

        JPanel middlePanel = new JPanel();
        middlePanel.setPreferredSize(new Dimension(800,350));
        middlePanel.add(button, BorderLayout.CENTER);
        middlePanel.setBackground(Color.blue);
        add(middlePanel, constraints);


    }

采用

constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1d;
constraints.weighty = 1d;

weighty weightx / weighty JavaDoc說:

指定如何分配額外的水平/垂直空間。

JavaDoc用於fill

當組件的顯示區域大於組件的請求大小時,將使用此字段。 它決定是否調整組件的大小,如果是,則如何。

不幸的是,使用GridBagLayout ,如果內容沒有填充它所在的整個容器,它將自動將其所有內容集中在其容器中。 這就是為什么你會有一個非常大的差距。

基本上有兩種方法可以解決這個問題:

  1. 困難的方法:擺​​弄GridBagConstraints 在試圖避免集中行為時,我的成功有限。
  2. 簡單的方法:將GridBagLayout放在FlowLayout ,然后將FlowLayout的對齊方式設置為左上角或任何你想要的。

我上周某個時候曾問過並回答過這個問題

因此,在您的情況下,您使用GridBagLayoutpanel1middlePanel直接添加到JFrame(?)

JFrame (GridBagLayout)
 - panel1
 - middlePanel

我會建議這個替代結構,以擺脫所有額外的空間(和中心對齊,如果你願意)。

JFrame (FlowLayout)
 - JPanel (GridBagLayout)
   - panel1
   - middlePanel

HTH

暫無
暫無

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

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