pack()
是extends自Window类的方法
使此窗口的大小适合其子组件的首选大小和布局。如果其中一个尺寸小于上一次调用setMinimumSize方法指定的最小尺寸,则会自动放大窗口的宽度和高度。
如果窗口和/或其所有者还不可显示,则在计算首选大小之前,将使它们都可显示。在计算窗口的大小后对其进行验证。
@SuppressWarnings("deprecation")public void pack() {Container parent = this.parent;if (parent != null && parent.peer == null) {parent.addNotify();}if (peer == null) {addNotify();}Dimension newSize = getPreferredSize();if (peer != null) {setClientSize(newSize.width, newSize.height);}if(beforeFirstShow) {isPacked = true;}validateUnconditionally();}
例1 , 外容器会变成子组件的大小
import javax.swing.*;import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;public class Pack测试231219 {public static JFrame frame = new JFrame(Thread.currentThread().getStackTrace()[1].getClassName());static{frame.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {super.windowClosing(e);System.exit(0);}});frame.setBounds(100,100,1024,768);}static void init() {}static void step1() {int sleep = 3000;JLabel jlb = new JLabel("""<html><style>#div001{ padding:100px 50px; }.c1{font-size:16px; color:blue;}</style><div id="div001" style="background:red; ">"""+"<center class=c1 >"+sleep+"毫秒后</center>"+"<center class=c1 >"+"调用frame.pack()"+"</center>"+"""</div></html> """);jlb.setOpaque(true);jlb.setBackground(Color.DARK_GRAY);jlb.setHorizontalAlignment(JLabel.CENTER);jlb.setVerticalAlignment(JLabel.CENTER);frame.add(jlb, BorderLayout.CENTER);try {frame.setVisible(true);Thread.sleep(sleep);frame.pack();}catch(Exception ex) {ex.printStackTrace();}}static void step2() {}public static void main(String[] arguments)throws Exception {init(); step1(); step2 ();}}
效果
例2 , 如果子组件设置了 setPreferredSize() , 外容器会变成子组件setPreferredSize()的大小
这个例子中jlb.setPreferredSize(new Dimension(600,600));
jlb.setSize()无效
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class Pack测试231220 {public static JFrame frame = new JFrame(Thread.currentThread().getStackTrace()[1].getClassName());static{frame.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {super.windowClosing(e);System.exit(0);}});frame.setBounds(100,100,1024,768);}static void init() {}static void step1() {int sleep = 3000;JLabel jlb = new JLabel("""<html><style>#div001{ padding:100px 50px; }.c1{font-size:16px; color:blue;}</style><div id="div001" style="background:red; ">"""+"<center class=c1 >"+sleep+"毫秒后</center>"+"<center class=c1 >"+"调用frame.pack()"+"</center>"+"""</div></html> """);jlb.setOpaque(true);jlb.setBackground(Color.DARK_GRAY);jlb.setHorizontalAlignment(JLabel.CENTER);jlb.setVerticalAlignment(JLabel.CENTER);frame.add(jlb, BorderLayout.CENTER);try {frame.setVisible(true);Thread.sleep(sleep);jlb.setPreferredSize(new Dimension(600,600));frame.pack();}catch(Exception ex) {ex.printStackTrace();}}static void step2() {}public static void main(String[] arguments)throws Exception {init(); step1(); step2 ();}}