Image

Imagebanana wrote in Imagejava_dev

Maximising a JFrame

I want to keep track of the current position of a JFrame so that I can put it back in the same place next time it's created, so I have listeners for moves and resizes. I also have a listener for maximisation: if the user maximises the window, I want the stored size and position to stay unchanged. If the user closes the JFrame when it's maximised and then re-opens it, I want then to be able to un-maximise the JFrame to its previous size.

This seems straightforward enough, but there's a snag. When the JFrame is maximised, the sequence of events seems to be:

Moved: (top left, same size as before)
State changed: maximised
Resized: (top left, large as possible)


There's an "extra" move, which is indistinguishable from the user moving the window to the top left, except that it is shortly followed by a state change. The result of this is that if the user closes a maximised JFrame, re-opens it and un-maximises it, it's attached itself to the top left of the screen, instead of going back where it should be.

Here's a simplified example that shows the event sequence:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MaxTest
      extends JFrame
{
   MaxTest ()
   {
      super ( "MaxTest" );
      setDefaultCloseOperation ( EXIT_ON_CLOSE );
      addWindowStateListener
      (
         new WindowStateListener ()
         {
            public void windowStateChanged ( WindowEvent e )
            {
               showEvent ( "Window state changed", e );
            }
         }
      );
      addComponentListener
      (
         new ComponentAdapter ()
         {
            public void componentMoved ( ComponentEvent e )
            {
               showEvent ( "Window moved", e );
            }

            public void componentResized ( ComponentEvent e )
            {
               showEvent ( "Window resized", e );
            }
         }
      );
      add ( new JLabel ( "Maximise me!" ) );
      pack ();
      setVisible ( true );
   }

   public static void main ( String [] args )
   {
      new MaxTest ();
   }

   static void showEvent ( String msg, AWTEvent e )
   {
      System.out.println ( System.currentTimeMillis () + " " + msg + ": " + e );
   }
}


Any suggestions?