I'm putting together a quick and dirty animation using swing. I would like the window to be maximized. How can I do that?
By default, we can minimize a JFrame by clicking on minimize button and maximize a JFrame by clicking on maximize button at the top-right position of the screen. We can also do programmatically by using setState(JFrame. ICONIFIED) to minimize a JFrame and setState(JFrame. MAXIMIZED_BOTH) to maximize a JFrame.
setSize() and frame. pack() . You should use one of them at one time. Using setSize() you can give the size of frame you want but if you use pack() , it will automatically change the size of the frames according to the size of components in it.
The setSize(400,300) method of JFrame makes the rectangular area 400 pixels wide by 300 pixels high. The default size of a frame is 0 by 0 pixels. The setVisible(true) method makes the frame appear on the screen.
getScreenSize(); // get 2/3 of the height, and 2/3 of the width int height = screenSize. height * 2 / 3; int width = screenSize. width * 2 / 3; // set the jframe height and width jframe. setPreferredSize(new Dimension(width, height));
Provided that you are extending JFrame:
public void run() { MyFrame myFrame = new MyFrame(); myFrame.setVisible(true); myFrame.setExtendedState(myFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH); }
Something like this.setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);
import java.awt.*; import javax.swing.*; public class Test extends JFrame { public Test() { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); this.setMaximizedBounds(env.getMaximumWindowBounds()); this.setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH); } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); Test t = new Test(); t.setVisible(true); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With