Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Client Scripting
Expertise: Beginner
Aug 10, 1999

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 will maximize an internal frame, but that only works when your all your windows are contained within a JFrame. Frames, Windows, and JFrames cannot be maximized with a simple method call. You can work around this limitation by querying the system for the screen size and explicitly setting the size of the window.

The only problem is that after you include the native window system's borders and title bar, the window may exceed the size of the screen. Some window systems will not allow this and automatically resize the window to completely fit the screen. When you maximize a window in this manner, you will want to save the original dimensions of the window so you can restore them later. The following program demonstrates how to do this. It creates a Frame containing a button that will maximize or restore the window 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 Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap