Thursday, March 12, 2009

Tutorial on how to maximize the JFrame dynamically on display of JFrame

Here is a simple article which tells how to display a JFrame which is in the Maximized state.

Maximized state here refers to maximum size of JFrame on a desktop screen however not covering the taskbar.

This state of JFrame is sometimes needed so that a programmer can design the layout keeping in mind the maximum size which a JFrame can attain in a screen.

The code for such a frame will be:-

import java.awt.*;

import javax.swing.*;

public class MaxFrame

{

public static void main(String[] args)

{ GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();

JFrame f=new JFrame();

JPanel p =new JPanel();

f.add(p);

f.setMaximizedBounds(e.getMaximumWindowBounds());

f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

}

}

So put the setExtendedState code just before the f.setVisible(true) line. Also an important point is don't use the f.pack() or f.setResizable(false) in this code.

However this approach is not good when you don't want the user to resize the frame using the restore button as normally you would use setResizable(false) in the above code, but sometimes in that case, JFrame opens in minimized mode, why?? well i could not figure it out as well. So a code which does work smoothly all the time is needed.

So if you want the maximized frame to have no resizability in that case: we need to use below code.

import java.awt.*;

import javax.swing.*;

public class MaxFrame

{

public static void main(String[] args)

{ GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();

JFrame f=new JFrame();

JPanel p =new JPanel();

f.add(p);

f.setMaximizedBounds(e.getMaximumWindowBounds());

f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );

f.setSize(e.getMaximumWindowBounds().width, e.getMaximumWindowBounds().height);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setResizable(false);

f.setVisible(true);

}

}

The above code thus gives a basic idea of how to create a maximized frame both with resizability and without resizability, and not covering the taskbar.

Hope you liked the article, then please consider bookmarking it. Thanks!!

No comments:

Post a Comment

Write Your Comments..

Share this Page:-