下面的程序是用 gridbaglayout 将 jpanel 定位在 jframe 的左上角,但在 jframe 的中心显示一个非常小的框。当我将 jframe 的布局设置为 null 时,jpanel 显示正常。有人能告诉我为什么 jpanel 用 gridbaglayout 压缩到框架的中心吗?我真的需要使用gridbag。请帮忙
import java.awt.*;
import javax.swing.*; //swing package
public class Major {
//defining the constructor
public Major() {
JFrame maFrame = new JFrame("The main screen"); //creating main Jframe
JPanel headPanel = new JPanel(); //creating the header panel
maFrame.setSize(900, 700); //setting size
maFrame.setBackground(Color.LIGHT_GRAY); //setting color of frame
Container container = maFrame.getContentPane();
container.setLayout(new GridBagLayout()); //setting layout of main frame
GridBagConstraints cns = new GridBagConstraints(); //creating constraint
cns.gridx = 0;
cns.gridy = 0;
maFrame.setLocationRelativeTo(null); //centering frame
headPanel.setBackground(Color.WHITE);
headPanel.setSize(200, 150);
container.add(headPanel, cns);
maFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting the default close operation of JFrame
maFrame.setVisible(true); //making the frame visible
}
//defining the main method
public static void main(String[] args) {
new Major(); //instantiating the class
}
}