.pack() 有什么作用?
我正在学习JPanel和GridLayout,这段代码片段将生成一个带有6个按钮的简单JPanel。
package testing;
import java.io.*;
import java.util.*;
import java.security.*;
import javax.xml.bind.DatatypeConverter;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
public class Testing
{
public static class GridPanel extends JPanel
{
public GridPanel()
{
setLayout(new GridLayout(2,3));
setBackground(Color.GREEN);
this.setPreferredSize(new Dimension(500,500));
JButton b1 = new JButton ("Button 1");
JButton b2 = new JButton ("Button 2");
JButton b3 = new JButton ("Button 3");
JButton b4 = new JButton ("Button 4");
JButton b5 = new JButton ("Button 5");
JButton b6 = new JButton ("Button 6");
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
}
}
public static void main(String[] args)
{
GridPanel gp = new GridPanel();
JFrame jf = new JFrame();
jf.add(gp);
jf.pack(); //code wouldnt work if i comment out this line
jf.setVisible(true);
}
}
我想知道为什么我的代码不能工作,如果我注释掉jf.pack()