FileDocCategorySizeDatePackage
JFrame.javaAPI DocJava SE 5 API29474Fri Aug 26 14:57:54 BST 2005javax.swing

JFrame

public class JFrame extends Frame implements WindowConstants, RootPaneContainer, Accessible
An extended version of java.awt.Frame that adds support for the JFC/Swing component architecture. You can find task-oriented documentation about using JFrame in The Java Tutorial, in the section How to Make Frames.

The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. As a conveniance add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary. This means you can write:

frame.add(child);
And the child will be added to the contentPane. The content pane will always be non-null. Attempting to set it to null will cause the JFrame to throw an exception. The default content pane will have a BorderLayout manager set on it. Refer to {@link javax.swing.RootPaneContainer} for details on adding, removing and setting the LayoutManager of a JFrame.

Unlike a Frame, a JFrame has some notion of how to respond when the user attempts to close the window. The default behavior is to simply hide the JFrame when the user closes the window. To change the default behavior, you invoke the method {@link #setDefaultCloseOperation}. To make the JFrame behave the same as a Frame instance, use setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE).

For more information on content panes and other features that root panes provide, see Using Top-Level Containers in The Java Tutorial.

In a multi-screen environment, you can create a JFrame on a different screen device. See {@link java.awt.Frame} for more information.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see {@link java.beans.XMLEncoder}.

see
JRootPane
see
#setDefaultCloseOperation
see
java.awt.event.WindowListener#windowClosing
see
javax.swing.RootPaneContainer
beaninfo
attribute: isContainer true attribute: containerDelegate getContentPane description: A toplevel window which can be minimized to an icon.
version
1.104 12/19/03
author
Jeff Dinkins
author
Georges Saab
author
David Kloba

Fields Summary
public static final int
EXIT_ON_CLOSE
The exit application default window close operation. If a window has this set as the close operation and is closed in an applet, a SecurityException may be thrown. It is recommended you only use this in an application.

private static final Object
defaultLookAndFeelDecoratedKey
Key into the AppContext, used to check if should provide decorations by default.
private int
defaultCloseOperation
protected JRootPane
rootPane
The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.
protected boolean
rootPaneCheckingEnabled
If true then calls to add and setLayout will be forwarded to the contentPane. This is initially false, but is set to true when the JFrame is constructed.
protected AccessibleContext
accessibleContext
The accessible context property.
Constructors Summary
public JFrame()
Constructs a new frame that is initially invisible.

This constructor sets the component's locale property to the value returned by JComponent.getDefaultLocale.

exception
HeadlessException if GraphicsEnvironment.isHeadless() returns true.
see
java.awt.GraphicsEnvironment#isHeadless
see
Component#setSize
see
Component#setVisible
see
JComponent#getDefaultLocale



                                              
        
        super();        
        frameInit();
    
public JFrame(GraphicsConfiguration gc)
Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.

This constructor sets the component's locale property to the value returned by JComponent.getDefaultLocale.

param
gc the GraphicsConfiguration that is used to construct the new Frame; 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
JComponent#getDefaultLocale
since
1.3

        super(gc);
        frameInit();
    
public JFrame(String title)
Creates a new, initially invisible Frame with the specified title.

This constructor sets the component's locale property to the value returned by JComponent.getDefaultLocale.

param
title the title for the frame
exception
HeadlessException if GraphicsEnvironment.isHeadless() returns true.
see
java.awt.GraphicsEnvironment#isHeadless
see
Component#setSize
see
Component#setVisible
see
JComponent#getDefaultLocale

        super(title);
        frameInit();
    
public JFrame(String title, GraphicsConfiguration gc)
Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.

This constructor sets the component's locale property to the value returned by JComponent.getDefaultLocale.

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 that is used to construct the new JFrame with; 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
JComponent#getDefaultLocale
since
1.3

        super(title, gc);
        frameInit();
    
Methods Summary
protected voidaddImpl(java.awt.Component comp, java.lang.Object constraints, int index)
Adds the specified child Component. This method is overridden to conditionally forwad calls to the contentPane. By default, children are added to the contentPane instead of the frame, refer to {@link javax.swing.RootPaneContainer} for details.

param
comp the component to be enhanced
param
constraints the constraints to be respected
param
index the index
exception
IllegalArgumentException if index is invalid
exception
IllegalArgumentException if adding the container's parent to itself
exception
IllegalArgumentException if adding a window to a container
see
#setRootPaneCheckingEnabled
see
javax.swing.RootPaneContainer

        if(isRootPaneCheckingEnabled()) {
            getContentPane().add(comp, constraints, index);
        }
        else {
            super.addImpl(comp, constraints, index);
        }
    
protected javax.swing.JRootPanecreateRootPane()
Called by the constructor methods to create the default rootPane.

        JRootPane rp = new JRootPane();
        // NOTE: this uses setOpaque vs LookAndFeel.installProperty as there
        // is NO reason for the RootPane not to be opaque. For painting to
        // work the contentPane must be opaque, therefor the RootPane can
        // also be opaque.
        rp.setOpaque(true);
        return rp;
    
protected voidframeInit()
Called by the constructors to init the JFrame properly.

        enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK);
        setLocale( JComponent.getDefaultLocale() );
        setRootPane(createRootPane());
        setBackground(UIManager.getColor("control"));
        setRootPaneCheckingEnabled(true);
        if (JFrame.isDefaultLookAndFeelDecorated()) {
            boolean supportsWindowDecorations = 
            UIManager.getLookAndFeel().getSupportsWindowDecorations();
            if (supportsWindowDecorations) {
                setUndecorated(true);
                getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
            }
        }
        sun.awt.SunToolkit.checkAndSetPolicy(this, true);
    
public javax.accessibility.AccessibleContextgetAccessibleContext()
Gets the AccessibleContext associated with this JFrame. For JFrames, the AccessibleContext takes the form of an AccessibleJFrame. A new AccessibleJFrame instance is created if necessary.

return
an AccessibleJFrame that serves as the AccessibleContext of this JFrame


                                                         
       
        if (accessibleContext == null) {
            accessibleContext = new AccessibleJFrame();
        }
        return accessibleContext;
    
public java.awt.ContainergetContentPane()
Returns the contentPane object for this frame.

return
the contentPane property
see
#setContentPane
see
RootPaneContainer#getContentPane

 
        return getRootPane().getContentPane(); 
    
public intgetDefaultCloseOperation()
Returns the operation that occurs when the user initiates a "close" on this frame.

return
an integer indicating the window-close operation
see
#setDefaultCloseOperation

        return defaultCloseOperation;
    
public java.awt.ComponentgetGlassPane()
Returns the glassPane object for this frame.

return
the glassPane property
see
#setGlassPane
see
RootPaneContainer#getGlassPane

 
        return getRootPane().getGlassPane(); 
    
public javax.swing.JMenuBargetJMenuBar()
Returns the menubar set on this frame.

return
the menubar for this frame
see
#setJMenuBar

 
        return getRootPane().getMenuBar(); 
    
public javax.swing.JLayeredPanegetLayeredPane()
Returns the layeredPane object for this frame.

return
the layeredPane property
see
#setLayeredPane
see
RootPaneContainer#getLayeredPane

 
        return getRootPane().getLayeredPane(); 
    
public javax.swing.JRootPanegetRootPane()
Returns the rootPane object for this frame.

return
the rootPane property
see
#setRootPane
see
RootPaneContainer#getRootPane

 
        return rootPane; 
    
public static booleanisDefaultLookAndFeelDecorated()
Returns true if newly created JFrames should have their Window decorations provided by the current look and feel. This is only a hint, as certain look and feels may not support this feature.

return
true if look and feel should provide Window decorations.
since
1.4

    
        Boolean defaultLookAndFeelDecorated = 
            (Boolean) SwingUtilities.appContextGet(defaultLookAndFeelDecoratedKey);
        if (defaultLookAndFeelDecorated == null) {
            defaultLookAndFeelDecorated = Boolean.FALSE;
        }
        return defaultLookAndFeelDecorated.booleanValue();
    
protected booleanisRootPaneCheckingEnabled()
Returns whether calls to add and setLayout are forwarded to the contentPane.

return
true if add and setLayout are fowarded; false otherwise
see
#addImpl
see
#setLayout
see
#setRootPaneCheckingEnabled
see
javax.swing.RootPaneContainer

        return rootPaneCheckingEnabled;
    
protected java.lang.StringparamString()
Returns a string representation of this JFrame. 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
a string representation of this JFrame

        String defaultCloseOperationString;
        if (defaultCloseOperation == HIDE_ON_CLOSE) {
            defaultCloseOperationString = "HIDE_ON_CLOSE";
        } else if (defaultCloseOperation == DISPOSE_ON_CLOSE) {
            defaultCloseOperationString = "DISPOSE_ON_CLOSE";
        } else if (defaultCloseOperation == DO_NOTHING_ON_CLOSE) {
            defaultCloseOperationString = "DO_NOTHING_ON_CLOSE";
        } else if (defaultCloseOperation == 3) {
            defaultCloseOperationString = "EXIT_ON_CLOSE";
        } else defaultCloseOperationString = "";
	String rootPaneString = (rootPane != null ?
				 rootPane.toString() : "");
	String rootPaneCheckingEnabledString = (rootPaneCheckingEnabled ?
						"true" : "false");

	return super.paramString() +
	",defaultCloseOperation=" + defaultCloseOperationString +
	",rootPane=" + rootPaneString +
	",rootPaneCheckingEnabled=" + rootPaneCheckingEnabledString;
    
protected voidprocessWindowEvent(java.awt.event.WindowEvent e)
Processes window events occurring on this component. Hides the window or disposes of it, as specified by the setting of the defaultCloseOperation property.

param
e the window event
see
#setDefaultCloseOperation
see
java.awt.Window#processWindowEvent

        super.processWindowEvent(e);

        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            switch(defaultCloseOperation) {
              case HIDE_ON_CLOSE:
                 setVisible(false);
                 break;
              case DISPOSE_ON_CLOSE:
                 setVisible(false);
                 dispose();
                 break;
              case DO_NOTHING_ON_CLOSE:
                 default: 
                 break;
	      case EXIT_ON_CLOSE:
                  // This needs to match the checkExit call in
                  // setDefaultCloseOperation
		System.exit(0);
		break;
            }
        }
    
public voidremove(java.awt.Component comp)
Removes the specified component from the container. If comp is not the rootPane, this will forward the call to the contentPane. This will do nothing if comp is not a child of the JFrame or contentPane.

param
comp the component to be removed
throws
NullPointerException if comp is null
see
#add
see
javax.swing.RootPaneContainer

	if (comp == rootPane) {
	    super.remove(comp);
	} else {
	    getContentPane().remove(comp);
	}
    
public voidsetContentPane(java.awt.Container contentPane)
Sets the contentPane property. This method is called by the constructor.

Swing's painting architecture requires an opaque JComponent in the containment hiearchy. This is typically provided by the content pane. If you replace the content pane it is recommended you replace it with an opaque JComponent.

param
contentPane the contentPane object for this frame
exception
java.awt.IllegalComponentStateException (a runtime exception) if the content pane parameter is null
see
#getContentPane
see
RootPaneContainer#setContentPane
see
JRootPane
beaninfo
hidden: true description: The client area of the frame where child components are normally inserted.

        getRootPane().setContentPane(contentPane);
    
public voidsetDefaultCloseOperation(int operation)
Sets the operation that will happen by default when the user initiates a "close" on this frame. You must specify one of the following choices:

  • DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.
  • HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.
  • DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.
  • EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.

The value is set to HIDE_ON_CLOSE by default.

Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.

param
operation the operation which should be performed when the user closes the frame
exception
IllegalArgumentException if defaultCloseOperation value isn't one of the above valid values
see
#addWindowListener
see
#getDefaultCloseOperation
see
WindowConstants
throws
SecurityException if EXIT_ON_CLOSE has been specified and the SecurityManager will not allow the caller to invoke System.exit
see
java.lang.Runtime#exit(int)
beaninfo
preferred: true bound: true enum: DO_NOTHING_ON_CLOSE WindowConstants.DO_NOTHING_ON_CLOSE HIDE_ON_CLOSE WindowConstants.HIDE_ON_CLOSE DISPOSE_ON_CLOSE WindowConstants.DISPOSE_ON_CLOSE EXIT_ON_CLOSE WindowConstants.EXIT_ON_CLOSE description: The frame's default close operation.

	if (operation != DO_NOTHING_ON_CLOSE &&
	    operation != HIDE_ON_CLOSE &&
	    operation != DISPOSE_ON_CLOSE &&
	    operation != EXIT_ON_CLOSE) {
            throw new IllegalArgumentException("defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE, or EXIT_ON_CLOSE");
	}
        if (this.defaultCloseOperation != operation) {
            if (operation == EXIT_ON_CLOSE) {
                SecurityManager security = System.getSecurityManager();
                if (security != null) {
                    security.checkExit(0);
                }
            }
            int oldValue = this.defaultCloseOperation;
            this.defaultCloseOperation = operation;
            firePropertyChange("defaultCloseOperation", oldValue, operation);
	}
    
public static voidsetDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated)
Provides a hint as to whether or not newly created JFrames should have their Window decorations (such as borders, widgets to close the window, title...) provided by the current look and feel. If defaultLookAndFeelDecorated is true, the current LookAndFeel supports providing window decorations, and the current window manager supports undecorated windows, then newly created JFrames will have their Window decorations provided by the current LookAndFeel. Otherwise, newly created JFrames will have their Window decorations provided by the current window manager.

You can get the same effect on a single JFrame by doing the following:

JFrame frame = new JFrame();
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);

param
defaultLookAndFeelDecorated A hint as to whether or not current look and feel should provide window decorations
see
javax.swing.LookAndFeel#getSupportsWindowDecorations
since
1.4

        if (defaultLookAndFeelDecorated) {
            SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.TRUE);
        } else {
            SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.FALSE);
        }
    
public voidsetGlassPane(java.awt.Component glassPane)
Sets the glassPane property. This method is called by the constructor.

param
glassPane the glassPane object for this frame
see
#getGlassPane
see
RootPaneContainer#setGlassPane
beaninfo
hidden: true description: A transparent pane used for menu rendering.

        getRootPane().setGlassPane(glassPane);
    
public voidsetIconImage(java.awt.Image image)

        Image oldImage = getIconImage();
        super.setIconImage(image);
        firePropertyChange("iconImage", oldImage, image);
    
public voidsetJMenuBar(javax.swing.JMenuBar menubar)
Sets the menubar for this frame.

param
menubar the menubar being placed in the frame
see
#getJMenuBar
beaninfo
hidden: true description: The menubar for accessing pulldown menus from this frame.

        getRootPane().setMenuBar(menubar);
    
public voidsetLayeredPane(javax.swing.JLayeredPane layeredPane)
Sets the layeredPane property. This method is called by the constructor.

param
layeredPane the layeredPane object for this frame
exception
java.awt.IllegalComponentStateException (a runtime exception) if the layered pane parameter is null
see
#getLayeredPane
see
RootPaneContainer#setLayeredPane
beaninfo
hidden: true description: The pane that holds the various frame layers.

        getRootPane().setLayeredPane(layeredPane);
    
public voidsetLayout(java.awt.LayoutManager manager)
Sets the LayoutManager. Overridden to conditionally forward the call to the contentPane. Refer to {@link javax.swing.RootPaneContainer} for more information.

param
manager the LayoutManager
see
#setRootPaneCheckingEnabled
see
javax.swing.RootPaneContainer

        if(isRootPaneCheckingEnabled()) {
            getContentPane().setLayout(manager);
        }
        else {
            super.setLayout(manager);
        }
    
protected voidsetRootPane(javax.swing.JRootPane root)
Sets the rootPane property. This method is called by the constructor.

param
root the rootPane object for this frame
see
#getRootPane
beaninfo
hidden: true description: the RootPane object for this frame.

        if(rootPane != null) {
            remove(rootPane);
        }
        rootPane = root;
        if(rootPane != null) {
            boolean checkingEnabled = isRootPaneCheckingEnabled();
            try {
                setRootPaneCheckingEnabled(false);
                add(rootPane, BorderLayout.CENTER);
            }
            finally {
                setRootPaneCheckingEnabled(checkingEnabled);
            }
        }
    
protected voidsetRootPaneCheckingEnabled(boolean enabled)
Sets whether calls to add and setLayout are forwarded to the contentPane.

param
enabled true if add and setLayout are forwarded, false if they should operate directly on the JFrame.
see
#addImpl
see
#setLayout
see
#isRootPaneCheckingEnabled
see
javax.swing.RootPaneContainer
beaninfo
hidden: true description: Whether the add and setLayout methods are forwarded

        rootPaneCheckingEnabled = enabled;
    
public voidupdate(java.awt.Graphics g)
Just calls paint(g). This method was overridden to prevent an unnecessary call to clear the background.

param
g the Graphics context in which to paint

        paint(g);