FileDocCategorySizeDatePackage
Frame.javaAPI DocJava SE 5 API38489Fri Aug 26 14:56:44 BST 2005java.awt

Frame

public class Frame extends Window implements MenuContainer
A Frame is a top-level window with a title and a border.

The size of the frame includes any area designated for the border. The dimensions of the border area may be obtained using the getInsets method, however, since these dimensions are platform-dependent, a valid insets value cannot be obtained until the frame is made displayable by either calling pack or show. Since the border area is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left, insets.top), and has a size of width - (insets.left + insets.right) by height - (insets.top + insets.bottom).

The default layout for a frame is BorderLayout.

A frame may have its native decorations (i.e. Frame and Titlebar) turned off with setUndecorated. This can only be done while the frame is not {@link Component#isDisplayable() displayable}.

In a multi-screen environment, you can create a Frame on a different screen device by constructing the Frame with {@link #Frame(GraphicsConfiguration)} or {@link #Frame(String title, GraphicsConfiguration)}. The GraphicsConfiguration object is one of the GraphicsConfiguration objects of the target screen device.

In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices, the bounds of all configurations are relative to the virtual-coordinate system. The origin of the virtual-coordinate system is at the upper left-hand corner of the primary physical screen. Depending on the location of the primary screen in the virtual device, negative coordinates are possible, as shown in the following figure.

Diagram of virtual device encompassing three physical screens and one primary physical screen. The primary physical screen
shows (0,0) coords while a different physical screen shows (-80,-100) coords.

In such an environment, when calling setLocation, you must pass a virtual coordinate to this method. Similarly, calling getLocationOnScreen on a Frame returns virtual device coordinates. Call the getBounds method of a GraphicsConfiguration to find its origin in the virtual coordinate system.

The following code sets the location of the Frame at (10, 10) relative to the origin of the physical screen of the corresponding GraphicsConfiguration. If the bounds of the GraphicsConfiguration is not taken into account, the Frame location would be set at (10, 10) relative to the virtual-coordinate system and would appear on the primary physical screen, which might be different from the physical screen of the specified GraphicsConfiguration.

Frame f = new Frame(GraphicsConfiguration gc);
Rectangle bounds = gc.getBounds();
f.setLocation(10 + bounds.x, 10 + bounds.y);

Frames are capable of generating the following types of WindowEvents:

  • WINDOW_OPENED
  • WINDOW_CLOSING:
    If the program doesn't explicitly hide or dispose the window while processing this event, the window close operation is canceled.
  • WINDOW_CLOSED
  • WINDOW_ICONIFIED
  • WINDOW_DEICONIFIED
  • WINDOW_ACTIVATED
  • WINDOW_DEACTIVATED
  • WINDOW_GAINED_FOCUS
  • WINDOW_LOST_FOCUS
  • WINDOW_STATE_CHANGED
version
1.147, 05/18/04
author
Sami Shaio
see
WindowEvent
see
Window#addWindowListener
since
JDK1.0

Fields Summary
public static final int
DEFAULT_CURSOR
public static final int
CROSSHAIR_CURSOR
public static final int
TEXT_CURSOR
public static final int
WAIT_CURSOR
public static final int
SW_RESIZE_CURSOR
public static final int
SE_RESIZE_CURSOR
public static final int
NW_RESIZE_CURSOR
public static final int
NE_RESIZE_CURSOR
public static final int
N_RESIZE_CURSOR
public static final int
S_RESIZE_CURSOR
public static final int
W_RESIZE_CURSOR
public static final int
E_RESIZE_CURSOR
public static final int
HAND_CURSOR
public static final int
MOVE_CURSOR
public static final int
NORMAL
Frame is in the "normal" state. This symbolic constant names a frame state with all state bits cleared.
public static final int
ICONIFIED
This state bit indicates that frame is iconified.
public static final int
MAXIMIZED_HORIZ
This state bit indicates that frame is maximized in the horizontal direction.
public static final int
MAXIMIZED_VERT
This state bit indicates that frame is maximized in the vertical direction.
public static final int
MAXIMIZED_BOTH
This state bit mask indicates that frame is fully maximized (that is both horizontally and vertically). It is just a convenience alias for MAXIMIZED_VERT | MAXIMIZED_HORIZ.

Note that the correct test for frame being fully maximized is

(state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH

To test is frame is maximized in some direction use

(state & Frame.MAXIMIZED_BOTH) != 0
Rectangle
maximizedBounds
Maximized bounds for this frame.
String
title
This is the title of the frame. It can be changed at any time. title can be null and if this is the case the title = "".
transient Image
icon
icon is the graphical way we can represent the frame. icon can be null, but obviously if you try to set the icon image icon cannot be null.
MenuBar
menuBar
The frames menubar. If menuBar = null the frame will not have a menubar.
boolean
resizable
This field indicates whether the frame is resizable. This property can be changed at any time. resizable will be true if the frame is resizable, otherwise it will be false.
boolean
undecorated
This field indicates whether the frame is undecorated. This property can only be changed while the frame is not displayable. undecorated will be true if the frame is undecorated, otherwise it will be false.
boolean
mbManagement
mbManagement is only used by the Motif implementation.
private int
state
Vector
ownedWindows
private transient WeakReference
weakThis
private static final String
base
private static int
nameCounter
private static final long
serialVersionUID
private int
frameSerializedDataVersion
Frame's Serialized Data Version.
Constructors Summary
public Frame()
Constructs a new instance of Frame that is initially invisible. The title of the Frame is empty.

exception
HeadlessException when GraphicsEnvironment.isHeadless() returns true
see
java.awt.GraphicsEnvironment#isHeadless()
see
Component#setSize
see
Component#setVisible(boolean)


     
        /* ensure that the necessary native libraries are loaded */
	Toolkit.loadLibraries();
        if (!GraphicsEnvironment.isHeadless()) {
            initIDs();
        }
    
        this("");
    
public Frame(GraphicsConfiguration gc)
Create a Frame with the specified GraphicsConfiguration of a screen device.

param
gc the GraphicsConfiguration of the target screen device. If gc is null, the system default GraphicsConfiguration is assumed.
exception
IllegalArgumentException if gc is not from a screen device. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
see
java.awt.GraphicsEnvironment#isHeadless()
since
1.3

        this("", gc);
    
public Frame(String title)
Constructs a new, initially invisible Frame object with the specified title.

param
title the title to be displayed in the frame's border. A null value is treated as an empty string, "".
exception
HeadlessException when GraphicsEnvironment.isHeadless() returns true
see
java.awt.GraphicsEnvironment#isHeadless()
see
java.awt.Component#setSize
see
java.awt.Component#setVisible(boolean)
see
java.awt.GraphicsConfiguration#getBounds

        init(title, null);
    
public Frame(String title, GraphicsConfiguration gc)
Constructs a new, initially invisible Frame object with the specified title and a GraphicsConfiguration.

param
title the title to be displayed in the frame's border. A null value is treated as an empty string, "".
param
gc the GraphicsConfiguration of the target screen device. If gc is null, the system default GraphicsConfiguration is assumed.
exception
IllegalArgumentException if gc is not from a screen device. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
see
java.awt.GraphicsEnvironment#isHeadless()
see
java.awt.Component#setSize
see
java.awt.Component#setVisible(boolean)
see
java.awt.GraphicsConfiguration#getBounds

        super(gc);
        init(title, gc);
    
Methods Summary
public voidaddNotify()
Makes this Frame displayable by connecting it to a native screen resource. Making a frame displayable will cause any of its children to be made displayable. This method is called internally by the toolkit and should not be called directly by programs.

see
Component#isDisplayable
see
#removeNotify

	synchronized (getTreeLock()) {
	    if (peer == null) {
		peer = getToolkit().createFrame(this);
	    }
	    FramePeer p = (FramePeer)peer;
	    MenuBar menuBar = this.menuBar;
	    if (menuBar != null) {
	        mbManagement = true;
		menuBar.addNotify();
		p.setMenuBar(menuBar);
	    }
	    p.setMaximizedBounds(maximizedBounds);
	    super.addNotify();
	}
    
voidaddToFrameList()

        synchronized (Frame.class) {
            Vector frameList = (Vector)appContext.get(Frame.class);
            if (frameList == null) {
                frameList = new Vector();
                appContext.put(Frame.class, frameList);
            }
            frameList.addElement(weakThis);
        }
    
java.lang.StringconstructComponentName()
Construct a name for this component. Called by getName() when the name is null.

        synchronized (getClass()) {
	    return base + nameCounter++;
	}
    
protected voidfinalize()
Disposes of the input methods and context, and removes this Frame from the AppContext. Subclasses that override this method should call super.finalize().

        // We have to remove the (hard) reference to weakThis in the
        // AppContext's Frame list Vector, otherwise the WeakReference 
        // instance that points to this Frame will never get garbage 
        // collected.
        removeFromFrameList();
        super.finalize();
    
public javax.accessibility.AccessibleContextgetAccessibleContext()
Gets the AccessibleContext associated with this Frame. For frames, the AccessibleContext takes the form of an AccessibleAWTFrame. A new AccessibleAWTFrame instance is created if necessary.

return
an AccessibleAWTFrame that serves as the AccessibleContext of this Frame

        if (accessibleContext == null) {
            accessibleContext = new AccessibleAWTFrame();
        }
        return accessibleContext;
    
public intgetCursorType()

deprecated
As of JDK version 1.1, replaced by Component.getCursor().

	return (getCursor().getType());
    
public synchronized intgetExtendedState()
Gets the state of this frame. The state is represented as a bitwise mask.
  • NORMAL
    Indicates that no state bits are set.
  • ICONIFIED
  • MAXIMIZED_HORIZ
  • MAXIMIZED_VERT
  • MAXIMIZED_BOTH
    Concatenates MAXIMIZED_HORIZ and MAXIMIZED_VERT.

return
a bitwise mask of frame state constants
see
#setExtendedState(int)
since
1.4

        FramePeer peer = (FramePeer)this.peer;
        if (peer != null) {
            state = peer.getState();
        }
        return state;
    
public static java.awt.Frame[]getFrames()
Returns an array containing all Frames created by the application. If called from an applet, the array will only include the Frames accessible by that applet.

since
1.2

        synchronized (Frame.class) {
            Frame realCopy[];
            Vector frameList =
		(Vector)AppContext.getAppContext().get(Frame.class);
            if (frameList != null) {
	        // Recall that frameList is actually a Vector of WeakReferences
	        // and calling get() on one of these references may return
	        // null. Make two arrays-- one the size of the Vector 
	        // (fullCopy with size fullSize), and one the size of all
	        // non-null get()s (realCopy with size realSize).
	        int fullSize = frameList.size();
		int realSize = 0;
		Frame fullCopy[] = new Frame[fullSize];

		for (int i = 0; i < fullSize; i++) {
		    fullCopy[realSize] = (Frame) 
		        (((WeakReference) (frameList.elementAt(i))).get());

		    if (fullCopy[realSize] != null) {
		        realSize++;
		    }
		}

		if (fullSize != realSize) {
		    realCopy = new Frame[realSize];
		    System.arraycopy(fullCopy, 0, realCopy, 0, realSize);
		} else {
		    realCopy = fullCopy;
		}
            } else {
                realCopy = new Frame[0];
            }
            return realCopy;
        }
    
public java.awt.ImagegetIconImage()
Gets the image to be displayed in the minimized icon for this frame.

return
the icon image for this frame, or null if this frame doesn't have an icon image.
see
#setIconImage(Image)

	return icon;
    
public java.awt.RectanglegetMaximizedBounds()
Gets maximized bounds for this frame. Some fields may contain Integer.MAX_VALUE to indicate that system supplied values for this field must be used.

return
maximized bounds for this frame; may be null
see
#setMaximizedBounds(Rectangle)
since
1.4

	return maximizedBounds;
    
public java.awt.MenuBargetMenuBar()
Gets the menu bar for this frame.

return
the menu bar for this frame, or null if this frame doesn't have a menu bar.
see
#setMenuBar(MenuBar)

	return menuBar;
    
public synchronized intgetState()
Gets the state of this frame (obsolete).

In older versions of JDK a frame state could only be NORMAL or ICONIFIED. Since JDK 1.4 set of supported frame states is expanded and frame state is represented as a bitwise mask.

For compatibility with old programs this method still returns Frame.NORMAL and Frame.ICONIFIED but it only reports the iconic state of the frame, other aspects of frame state are not reported by this method.

return
Frame.NORMAL or Frame.ICONIFIED.
see
#setState(int)
see
#getExtendedState

        return (getExtendedState() & ICONIFIED) != 0 ? ICONIFIED : NORMAL;
    
public java.lang.StringgetTitle()
Gets the title of the frame. The title is displayed in the frame's border.

return
the title of this frame, or an empty string ("") if this frame doesn't have a title.
see
#setTitle(String)

	return title;
    
private voidinit(java.lang.String title, java.awt.GraphicsConfiguration gc)

        this.title = title;
        weakThis = new WeakReference(this);
        addToFrameList();
        SunToolkit.checkAndSetPolicy(this, false);
    
private static native voidinitIDs()
Initialize JNI field and method IDs

private booleanisFrameStateSupported(int state)

        if( !getToolkit().isFrameStateSupported( state ) ) {
            // * Toolkit.isFrameStateSupported returns always false 
            // on compound state even if all parts are supported;
            // * if part of state is not supported, state is not supported;
            // * MAXIMIZED_BOTH is not a compound state.
            if( ((state & ICONIFIED) != 0) &&
                !getToolkit().isFrameStateSupported( ICONIFIED )) {
                return false;
            }else {
                state &= ~ICONIFIED;
            }
            return getToolkit().isFrameStateSupported( state );
        }    
        return true;
    
public booleanisResizable()
Indicates whether this frame is resizable by the user. By default, all frames are initially resizable.

return
true if the user can resize this frame; false otherwise.
see
java.awt.Frame#setResizable(boolean)

	return resizable;
    
public booleanisUndecorated()
Indicates whether this frame is undecorated. By default, all frames are initially decorated.

return
true if frame is undecorated; false otherwise.
see
java.awt.Frame#setUndecorated(boolean)
since
1.4

        return undecorated;
    
protected java.lang.StringparamString()
Returns a string representing the state of this Frame. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null.

return
the parameter string of this frame

	String str = super.paramString();
	if (title != null) {
	    str += ",title=" + title;
	}
	if (resizable) {
	    str += ",resizable";
	}
	getExtendedState();	// sync with peer
	if (state == NORMAL) {
	    str += ",normal";
	}
	else {
	    if ((state & ICONIFIED) != 0) {
		str += ",iconified";
	    }
	    if ((state & MAXIMIZED_BOTH) == MAXIMIZED_BOTH) {
		str += ",maximized";
	    }
	    else if ((state & MAXIMIZED_HORIZ) != 0) {
		str += ",maximized_horiz";
	    }
	    else if ((state & MAXIMIZED_VERT) != 0) {
		str += ",maximized_vert";
	    }
	}
	return str;
    
voidpostProcessKeyEvent(java.awt.event.KeyEvent e)

        if (menuBar != null && menuBar.handleShortcut(e)) {
            e.consume();
            return;
        }
        super.postProcessKeyEvent(e);
    
private voidreadObject(java.io.ObjectInputStream s)
Reads the ObjectInputStream. Tries to read an Icon, which is optional data available as of 1.4. If an Icon is not available, but anything other than an EOF is detected, an OptionalDataException will be thrown.. Unrecognized keys or values will be ignored.

param
s the ObjectInputStream to read
exception
OptionalDataException if an Icon is not available, but anything other than an EOF is detected
exception
HeadlessException if GraphicsEnvironment.isHeadless returns true
see
java.awt.GraphicsEnvironment#isHeadless()
see
javax.swing.Icon
see
#writeObject(ObjectOutputStream)

      // HeadlessException is thrown by Window's readObject
      s.defaultReadObject();
      
      try {
 	  icon = (Image) s.readObject();
      } catch (java.io.OptionalDataException e) {
      // pre-1.4 instances will not have this optional data.
      // e.eof will be true to indicate that there is no more
      // data available for this object.

     // If e.eof is not true, throw the exception as it
     // might have been caused by unrelated reasons.
         if (!e.eof) {
             throw (e);
          }
      }

      if (menuBar != null)
	menuBar.parent = this;

      // Ensure 1.1 serialized Frames can read & hook-up
      // owned windows properly
      //
      if (ownedWindows != null) {
          for (int i = 0; i < ownedWindows.size(); i++) {
	      connectOwnedWindow((Window) ownedWindows.elementAt(i));
	  }
          ownedWindows = null;  
      }

      weakThis = new WeakReference(this);
      addToFrameList();
    
public voidremove(java.awt.MenuComponent m)
Removes the specified menu bar from this frame.

param
m the menu component to remove. If m is null, then no action is taken

	synchronized (getTreeLock()) {
	    if (m == menuBar) {
		menuBar = null;
		FramePeer peer = (FramePeer)this.peer;
		if (peer != null) {
		    mbManagement = true;
		    if (valid) {
		        invalidate();
		    }
		    peer.setMenuBar(null);
		    m.removeNotify();
		}
		m.parent = null;
	    } else {
		super.remove(m);
	    }
	}
    
voidremoveFromFrameList()

        synchronized (Frame.class) {
            Vector frameList = (Vector)appContext.get(Frame.class);
            if (frameList != null) {
                frameList.removeElement(weakThis);
            }
        }
    
public voidremoveNotify()
Makes this Frame undisplayable by removing its connection to its native screen resource. Making a Frame undisplayable will cause any of its children to be made undisplayable. This method is called by the toolkit internally and should not be called directly by programs.

see
Component#isDisplayable
see
#addNotify

        synchronized (getTreeLock()) {
	    FramePeer peer = (FramePeer)this.peer;
	    if (peer != null) {
                // get the latest Frame state before disposing
                getState();

                if (menuBar != null) {
	            mbManagement = true;
		    peer.setMenuBar(null);
		    menuBar.removeNotify();
                }
	    }
	    super.removeNotify();
	}
    
public voidsetCursor(int cursorType)

deprecated
As of JDK version 1.1, replaced by Component.setCursor(Cursor).

	if (cursorType < DEFAULT_CURSOR || cursorType > MOVE_CURSOR) {
	    throw new IllegalArgumentException("illegal cursor type");
	}
	setCursor(Cursor.getPredefinedCursor(cursorType));
    
public synchronized voidsetExtendedState(int state)
Sets the state of this frame. The state is represented as a bitwise mask.
  • NORMAL
    Indicates that no state bits are set.
  • ICONIFIED
  • MAXIMIZED_HORIZ
  • MAXIMIZED_VERT
  • MAXIMIZED_BOTH
    Concatenates MAXIMIZED_HORIZ and MAXIMIZED_VERT.

Note that if the state is not supported on a given platform, nothing will happen. The application may determine if a specific state is available via the java.awt.Toolkit#isFrameStateSupported(int state) method.

param
state a bitwise mask of frame state constants
see
#getExtendedState
see
java.awt.Toolkit#isFrameStateSupported(int)
since
1.4

        if ( !isFrameStateSupported( state ) ) {
            return;
        }    
        this.state = state;
        FramePeer peer = (FramePeer)this.peer;
        if (peer != null) {
            peer.setState(state);
        }
    
public synchronized voidsetIconImage(java.awt.Image image)
Sets the image to be displayed in the minimized icon for this frame. Not all platforms support the concept of minimizing a window.

param
image the icon image to be displayed. If this parameter is null then the icon image is set to the default image, which may vary with platform.
see
#getIconImage

	this.icon = image;
    	FramePeer peer = (FramePeer)this.peer;
	if (peer != null) {
	    peer.setIconImage(image);
	}
    
public synchronized voidsetMaximizedBounds(java.awt.Rectangle bounds)
Sets the maximized bounds for this frame.

When a frame is in maximized state the system supplies some defaults bounds. This method allows some or all of those system supplied values to be overridden.

If bounds is null, accept bounds supplied by the system. If non-null you can override some of the system supplied values while accepting others by setting those fields you want to accept from system to Integer.MAX_VALUE.

On some systems only the size portion of the bounds is taken into account.

param
bounds bounds for the maximized state
see
#getMaximizedBounds()
since
1.4

	this.maximizedBounds = bounds;
        FramePeer peer = (FramePeer)this.peer;
	if (peer != null) {
	    peer.setMaximizedBounds(bounds);
	}
    
public voidsetMenuBar(java.awt.MenuBar mb)
Sets the menu bar for this frame to the specified menu bar.

param
mb the menu bar being set. If this parameter is null then any existing menu bar on this frame is removed.
see
#getMenuBar

        synchronized (getTreeLock()) {
	    if (menuBar == mb) {
	        return;
	    }
	    if ((mb != null) && (mb.parent != null)) {
	        mb.parent.remove(mb);
	    }
	    if (menuBar != null) {
	        remove(menuBar);
	    }
	    menuBar = mb;
	    if (menuBar != null) {
	        menuBar.parent = this;

		FramePeer peer = (FramePeer)this.peer;
		if (peer != null) {
		    mbManagement = true;
		    menuBar.addNotify();
		    if (valid) {
		        invalidate();
		    }
		    peer.setMenuBar(menuBar);
		}
	    }
	}
    
public voidsetResizable(boolean resizable)
Sets whether this frame is resizable by the user.

param
resizable true if this frame is resizable; false otherwise.
see
java.awt.Frame#isResizable

        boolean oldResizable = this.resizable;
        boolean testvalid = false;

        synchronized (this) {
	    this.resizable = resizable;
	    FramePeer peer = (FramePeer)this.peer;
	    if (peer != null) {
	        peer.setResizable(resizable);
		testvalid = true;
	    }
	}

	// On some platforms, changing the resizable state affects
	// the insets of the Frame. If we could, we'd call invalidate()
	// from the peer, but we need to guarantee that we're not holding
	// the Frame lock when we call invalidate().
	if (testvalid && valid) {
	    invalidate();
	}
        firePropertyChange("resizable", oldResizable, resizable);
    
public synchronized voidsetState(int state)
Sets the state of this frame (obsolete).

In older versions of JDK a frame state could only be NORMAL or ICONIFIED. Since JDK 1.4 set of supported frame states is expanded and frame state is represented as a bitwise mask.

For compatibility with old programs this method still accepts Frame.NORMAL and Frame.ICONIFIED but it only changes the iconic state of the frame, other aspects of frame state are not affected by this method.

param
state either Frame.NORMAL or Frame.ICONIFIED.
see
#getState
see
#setExtendedState(int)

	int current = getExtendedState();
	if (state == ICONIFIED && (current & ICONIFIED) == 0) {
	    setExtendedState(current | ICONIFIED);
	}
	else if (state == NORMAL && (current & ICONIFIED) != 0) {
	    setExtendedState(current & ~ICONIFIED);
	}
    
public voidsetTitle(java.lang.String title)
Sets the title for this frame to the specified string.

param
title the title to be displayed in the frame's border. A null value is treated as an empty string, "".
see
#getTitle

        String oldTitle = this.title;
        if (title == null) {
            title = "";
        }


        synchronized(this) {
            this.title = title;
            FramePeer peer = (FramePeer)this.peer;
            if (peer != null) {
                peer.setTitle(title);
            }
        }
        firePropertyChange("title", oldTitle, title);
    
public voidsetUndecorated(boolean undecorated)
Disables or enables decorations for this frame. This method can only be called while the frame is not displayable.

param
undecorated true if no frame decorations are to be enabled; false if frame decorations are to be enabled.
throws
IllegalComponentStateException if the frame is displayable.
see
#isUndecorated
see
Component#isDisplayable
see
javax.swing.JFrame#setDefaultLookAndFeelDecorated(boolean)
since
1.4

        /* Make sure we don't run in the middle of peer creation.*/
        synchronized (getTreeLock()) {
            if (isDisplayable()) {
                throw new IllegalComponentStateException("The frame is displayable.");
            }
            this.undecorated = undecorated;
        }
    
private voidwriteObject(java.io.ObjectOutputStream s)
Writes default serializable fields to stream. Writes an optional serializable Icon, which is available as of 1.4.

param
s the ObjectOutputStream to write
serialData
an optional Icon
see
javax.swing.Icon
see
#readObject(ObjectInputStream)


                                         
       
        
    
      s.defaultWriteObject();
      if (icon instanceof Serializable) {
          s.writeObject(icon);
      }
      else
      {
          s.writeObject(null);
      }