pack()方法是Java中java.awt.Window類的一個方法,它用于調整窗口的大小以適應其內容
以下是如何在Java中正確使用pack()方法的示例:
import javax.swing.*;
import java.awt.*;
JFrame frame = new JFrame("Pack Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello, World!");
frame.getContentPane().add(label, BorderLayout.NORTH);
JButton button = new JButton("Click me!");
frame.getContentPane().add(button, BorderLayout.SOUTH);
pack()方法來調整窗口大?。?/li>
frame.pack();
frame.setVisible(true);
將上述代碼片段放在一起,完整的示例代碼如下:
import javax.swing.*;
import java.awt.*;
public class PackExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Pack Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello, World!");
frame.getContentPane().add(label, BorderLayout.NORTH);
JButton button = new JButton("Click me!");
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
運行此代碼將顯示一個窗口,其大小根據其內容(JLabel和JButton)進行調整。請注意,當你添加或刪除組件時,你可能需要再次調用pack()方法以更新窗口大小。