Maximize a JFrame
July 24, 2009 Leave a comment
Hello everyone,
I’m writing a new post because I saw an awfull code to maximize a JFrame in Java. Maybe You’ve ever tried to maximize Your GUI at the startup of Your application. It’s something which is very basic but which can be done in several ways (and some awfull ways too…).
First of all, You could retrieve the size of Your screen, and set it to Your JFrame like this :
// Get the screen size Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // Create a jframe, just for the example JFrame myFrame = new JFrame(); // Set the size myFrame.setPreferredSize(screen); myFrame.setVisible(true);
Well this is bad… Why? Because imagine You created Your application on Linux, and then try to launch it on Windows (I test an application recently…). On Linux, fine. On Windows, the application was under the task bar… So a part of the application was hidden… And the developpers used a similar code. So, this is not really a good practice.
There is a much simplier and efficient way to do that. Just look at this :
JFrame myFrame = new JFrame(); myFrame.setVisible(true); myFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
That’s all ! Much more simplier and better working. Notice that setting the state is after making the frame visible