0
使用GridBagLayout來放置面板如下。我想把所有東西都放在最上面。我可以用BorderLayout.NORTH我backgroundpanel(JP),但管理此則backgroundpanel犯規利用的GridBagLayout填滿窗口使用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);
}
}