- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When can we use the pack() method in Java?
The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes. An alternative to the pack() method is to establish a frame size explicitly by calling the setSize() or setBounds() methods. In general, using the pack() method is preferable to call than setSize() method, since pack leaves the frame layout manager in charge of the frame size and layout managers are good at adjusting to platform dependencies and other factors that affect the component size.
Syntax
public void pack()
Example
import java.awt.*; import javax.swing.*; public class PackMethodTest extends JFrame { public PackMethodTest() { setTitle("Pack() method Test"); setLayout(new FlowLayout()); setButton(); pack(); // calling the pack() method setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } void setButton() { for(int i=1; i < 6; i++) { add(new JButton("Button" +i)); } } public static void main(String args[]) { new PackMethodTest(); } }
Output
- Related Articles
- When can we use the getClass() method in Java?
- When can we use StackWalker.getCallerClass() method in Java 9?
- When can we use intern() method of String class in Java?
- When can we use a JSONStringer in Java?
- When can we use Synchronized blocks in Java?
- Can we use "this" keyword in a static method in java?
- How can we use this and super keywords in method reference in Java?
- When to use fillInStackTrace() method in Java?
- In SAP we can use the Java Connector
- Can we overload the main method in Java?
- Can we override the static method in Java?
- Can we override the equals() method in Java?
- Can we override the main method in java?
- Why can't we use the "super" keyword is in a static method in java?
- How can we use the StringTokenizer class in Java?

Advertisements