Change the size of JFrame - setPreferredSize()
There are several ways to change the dimension of JFrame, but the usual two methods are sufficient setPreferredSize and setSize of the JFrame.frame.setPreferredSize(new Dimension(350, 200)); |
Specifically, JFrame has 4 methods:
- setSize(): Resizes the component to length l and height h. The height and width values are automatically enlarged if they are less than the minimum size specified by the method. setMinimumSize.
- setMinimumSize(): Sets the minimum size that the window supports. If the current window size is less than the minimum size, the window dimension will automatically be expanded and adjusted to the new minimum size. If the setSize() and setBounds() are subsequently called by values lower than those specified by setMinimumSize(), the window will be automatically maximized to the minimum values.
- setMaximumSize(): Specifies the maximum size of the window with constant values as in setMinimumSize().
- setPreferredSize(): Specifies the preferred size of a component. This is the optimal size of the component and the right choice when you have a layout manager.
Example:
Here is a complete code that shows the appearance of JFrame with a resizing:
import java.awt.Dimension;References:
import javax.swing.JFrame;
public class Test extends JFrame{
public static void main(String[] args) {
//Create JFrame
JFrame jframe = new JFrame("JFrame resizing");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Change the dimension of JFrame
jframe.setPreferredSize(new Dimension(300, 200));
//Center JFrame
jframe.setLocationRelativeTo(null);
jframe.setVisible(true);
}
}
References:JPanel: setPreferredSize(Dimension preferredSize)
Setting minimum size limit for a window in java swing