使用GridBagLayout将内容与顶部对齐

时间:2016-11-03 20:41:25

标签: java swing alignment layout-manager gridbaglayout

我使用GridBagLayout将面板放置如下。我想把所有东西都对齐到顶部。我可以通过在我的background-panel(jp)上使用 BorderLayout.NORTH 来管理它,但后面的backgroundpanel没有填充窗口

如何使用GridBagLayout将面板对齐到顶部?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame {

    JPanel jp = new JPanel();
    JPanel jp1 = new JPanel();
    JPanel jp2 = new JPanel();
    JPanel jp3 = new JPanel();
    JPanel jp4 = new JPanel();

    public Test() {
        jp1.setPreferredSize(new Dimension(100, 100));
        jp2.setPreferredSize(new Dimension(100, 100));
        jp3.setPreferredSize(new Dimension(100, 100));
        jp4.setPreferredSize(new Dimension(100, 100));

        jp1.setBackground(Color.red);
        jp2.setBackground(Color.blue);
        jp3.setBackground(Color.yellow);
        jp4.setBackground(Color.green);

        GridBagLayout g = new GridBagLayout();
        jp.setLayout(g);
        jp.setBackground(Color.BLACK);

        GridBagConstraints con;
        con = new GridBagConstraints();
        con.insets = new Insets(3, 3, 3, 3); // top, left, bottom, right

        // PANEL ONE
        con.gridx = 0;
        con.gridy = 0;
        g.setConstraints(jp1, con);
        jp.add(jp1);

        // PANEL TWO
        con.gridx = 1;
        con.gridy = 0;
        g.setConstraints(jp2, con);
        jp.add(jp2);

        // PANEL THREE
        con.gridx = 0;
        con.gridy = 1;
        g.setConstraints(jp3, con);
        jp.add(jp3);

        // PANEL FOUR
        con.gridx = 1;
        con.gridy = 1;
        g.setConstraints(jp4, con);
        jp.add(jp4);

        this.setSize(600, 300);
        // I CAN MANAGE TO GET THE PANELS ALIGNED TO THE TOP BY USING BORDERLAYOUT
        // LIKE BELOW BUT THEN THE BACKGROUNDPANEL DOESNT FILL THE WINDOW
        // this.add(jp, BorderLayout.NORTH);

        this.add(jp);
    }

    public static void main(String[] args) {
        new Test().setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:2)

  

但后面的backgroundpanel没有填满窗口

为什么要让backgroundPanel填充窗口?

如果您只想要黑色背景,那么您可以这样做:

//this.add(jp);
this.getContentPane().setBackground( jp.getBackground() );
this.add(jp, BorderLayout.NORTH);

或者在使用GridBagLayout时,您需要指定“锚点”和“重量级”约束:

con.gridx = 0;
con.gridy = 0;
con.anchor = ...;

 ...

con.gridx = 1;
con.gridy = 1;
con.weighty = ...;

阅读How to Use GridBagLayout上的Swing教程中的部分,了解这些约束的作用。我已经指出了你需要使用哪些约束以及在你的例子中包含它们的位置。

另一种方法是使用包装面板:

JPanel wrapper = new JPanel();
wrapper.setBackground( Color.BLACK );
wrapper.add( jp );
this.add( wrapper );

默认情况下,JPanel使用FlowLayout,它将遵循添加到面板的任何组件的大小。