Maximize a JFrame

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🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: