devxlogo

Window Maximization

Window Maximization

Question:
How do you set the maximized state of a window within code?

Answer:
The Java AWT does not provide an interface for maximizing a window.The Swing JInternalFrame supports a setMaximum() method that willmaximize an internal frame, but that only works when your all yourwindows are contained within a JFrame. Frames, Windows, and JFramescannot be maximized with a simple method call. You can work around this limitation by querying the system for the screen size andexplicitly setting the size of the window.

The only problem is thatafter you include the native window system’s borders and title bar,the window may exceed the size of the screen. Some window systemswill not allow this and automatically resize the window to completelyfit the screen. When you maximize a window in this manner, you willwant to save the original dimensions of the window so you can restorethem later. The following program demonstrates how to do this. Itcreates a Frame containing a button that will maximize or restore thewindow size when pressed.

import java.awt.*;import java.awt.event.*;/** * Creates a window with a button that will maximize or restore the * size of the window when pressed. */public class Maximize extends Frame {  boolean _isMaximized = false;  int _oldWidth, _oldHeight;  Button _button;  public Maximize() {    _button = new Button("Maximize");    add(_button, BorderLayout.CENTER);    _button.addActionListener(new ActionListener() {	public void actionPerformed(ActionEvent e) {	  Toolkit toolkit = Toolkit.getDefaultToolkit();	  if(!_isMaximized) {	    Dimension screenSize = toolkit.getScreenSize();	    _oldWidth  = getWidth();	    _oldHeight = getHeight();	    setSize(screenSize.width, screenSize.height);	    _button.setLabel("Restore");	  } else {	    _button.setLabel("Maximize");	    setSize(_oldWidth, _oldHeight);	  }	  _isMaximized = !_isMaximized;	}      });  }  public static final void main(String[] args) {    Frame frame;    WindowListener exitListener;    frame  = new Maximize();    exitListener = new WindowAdapter() {      public void windowClosing(WindowEvent e) {        Window window = e.getWindow();        window.setVisible(false);        window.dispose();        System.exit(0);      }    };    frame.addWindowListener(exitListener);    frame.pack();    frame.setVisible(true);  }}

devx-admin

Share the Post: