|
Generated by JDiff |
||||||||
| PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES | |||||||||
This file contains all the changes in documentation in the packagejavax.swingas colored differences. Deletions are shownlike this, and additions are shown like this.
If no deletions or additions are shown in an entry, the HTML tags will be what has changed. The new HTML tags are shown in the differences. If no documentation existed, and then some was added in a later version, this change is noted in the appropriate class pages of differences, but the change is not shown on this page. Only changes in existing text are shown here. Similarly, documentation which was inherited from another class or interface is not shown here.
Note that an HTML error in the new documentation may cause the display of other documentation changes to be presented incorrectly. For instance, failure to close a <code> tag will cause all subsequent paragraphs to be displayed differently.
This class provides default implementations for the JFCActioninterface. Standard behaviors like the get and set methods forActionobject properties (icon text and enabled) are defined here. The developer need only subclass this abstract class and define theactionPerformedmethod.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.beanspackage. Please see java.beans.XMLEncoder @version 1.46 1247 02/0311/0102 @author Georges Saab @see Action
Defines common behaviors for buttons and menu items. For further information see How to Use Buttons Check Boxes and Radio Buttons a section in The Java Tutorial.Class AbstractButton, void setMnemonic(int)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.beanspackage. Please see java.beans.XMLEncoder @version 1.153 12156 04/0305/0102 @author Jeff Dinkins
Sets the keyboard mnemonic on the current model. The mnemonic is the key which when combined with the look and feel's mouseless modifier (usually Alt) will activate this button if focus is contained somewhere within this button's ancestor window.A mnemonic must correspond to a single key on the keyboard and should be specified using one of the
VK_XXXkeycodes defined injava.awt.event.KeyEvent. Mnemonics are case-insensitive therefore a key event with the corresponding keycode would cause the button to be activated whether or not the Shift modifier was pressed.If the character defined by the mnemonic is found within the button's label string the first occurrence of it will be underlined to indicate the mnemonic to the user.
If the corresponding character is not contained within the button's label then it will be displayed near the label in a look and feel dependent manner (commonly to the right surrounded by parenthesis).@param mnemonic the key code which represents the mnemonic @see java.awt.event.KeyEvent @see #setDisplayedMnemonicIndex @beaninfo bound: true attribute: visualUpdate true description: the keyboard character mnemonic
This class is used to create a multiple-exclusion scope for a set of buttons. Creating a set of buttons with the sameClass ButtonGroup, int getButtonCount()ButtonGroupobject means that turning "on" one of those buttons turns off all other buttons in the group.A
ButtonGroupcan be used with any set of objects that inherit fromAbstractButton. Typically a button group contains instances ofJRadioButtonJRadioButtonMenuItemorJToggleButton. It wouldn't make sense to put an instance ofJButtonorJMenuItemin a button group becauseJButtonandJMenuItemdon't implement the selected state.Initially all buttons in the group are unselected. Once any button is selected one button is always selected in the group. There is no way to turn a button programmatically to "off" in order to clear the button group. To give the appearance of "none selected" add an invisible radio button to the group and then programmatically select that button to turn off all the displayed radio buttons. For example a normal button with the label "none" could be wired to select the invisible radio button.
For examples and further information on using button groups see How to Use Radio Buttons a section in The Java Tutorial.
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.beanspackage. Please see java.beans.XMLEncoder @version 1.3233 12/0307/01 @author Jeff Dinkins
Returns the number of buttons in the group. @return the button count @since 1.3
The default editor for table and tree cells.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.beanspackage. Please see java.beans.XMLEncoder @version 1.46 1247 02/0311/0102 @author Alan Chung @author Philip Milne
This is an implementation of theDesktopManager. It currently implements the basic behaviors for managingJInternalFrames in an arbitrary parent.JInternalFrames that are not children of aJDesktopwill use this component to handle their desktop-like actions.This class provides a policy for the various JInternalFrame methods it is not meant to be called directly rather the various JInternalFrame methods will call into the DesktopManager.
@see JDesktopPane @see JInternalFrame @version 1.45 1246 04/0315/0102 @author David Kloba @author Steve Wilson
Default data model for list selections.Class DefaultListSelectionModel, void insertIndexInterval(int, int, boolean)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.beanspackage. Please see java.beans.XMLEncoder @version 1.65 1266 02/0313/0102 @author Philip Milne @author Hans Muller @see ListSelectionModel
Insert length indices beginning before/after index. If the value at index is itself selected and the selection mode is not SINGLE_SELECTION set all of the newly inserted itemsotherwiseas selected. Otherwise leave them unselected. This method is typically called to sync the selection model with a corresponding change in the data model.
DesktopManager objects are owned by a JDesktopPane object. They are responsible for implementing L&F specific behaviors for the JDesktopPane. JInternalFrame implementations should delegate specific behaviors to the DesktopManager. For instance if a JInternalFrame was asked to iconify it should try:getDesktopPane().getDesktopManager().iconifyFrame(frame);This delegation allows each L&F to provide custom behaviors for desktop-specific actions. (For example how and where the internal frame's icon would appear.)This class provides a policy for the various JInternalFrame methods it is not meant to be called directly rather the various JInternalFrame methods will call into the DesktopManager.
@see JDesktopPane @see JInternalFrame @see JInternalFrame.JDesktopIcon @version 1.12 1213 04/0315/0102 @author David Kloba
An implementation of a check box -- an item that can be selected or deselected and which displays its state to the user. By convention any number of check boxes in a group can be selected. See How to UseButtoncButtons Check Boxes and Radio Buttons in The Java Tutorial for examples and information on using check boxes.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JCheckBoxkey assignments.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.beanspackage. Please see java.beans.XMLEncoder @see JRadioButton @beaninfo attribute: isContainer false description: A component which can be selected or deselected. @version 1.686912/03/0112/02 @author Jeff Dinkins
Class JColorChooser, constructor JColorChooser(ColorSelectionModel)JColorChooserprovides a pane of controls designed to allow a user to manipulate and select a color. For information about using color choosers see How to Use Color Choosers a section in The Java Tutorial.This class provides three levels of API:
- A static convenience method which shows a modal color-chooser dialog and returns the color selected by the user.
- A static convenience method for creating a color-chooser dialog where
ActionListenerscan be specified to be invoked when the user presses one of the dialog buttons.- The ability to create instances of
JColorChooserpanes directly (within any container).PropertyChangelisteners can be added to detect when the current "color" property changes.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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component that supports selecting a Color. @version 1.414212/03/0120/02 @author James Gosling @author Amy Fowler @author Steve Wilson
Creates a color chooser pane with the specifiedClass JColorChooser, void setPreviewPanel(JComponent)ColorSelectionModel. @paraminitialColormodel theinitial color setColorSelectionModelin the chooserto be used
Sets the current preview panel. This will fire aPropertyChangeEventfor the property named "previewPanel". @paramcolorpreview thecolor to beJComponentset inwhich displays thecolorcurrentchoosercolor @see JComponent#addPropertyChangeListener @beaninfo bound: true hidden: true description: The UI component which displays the current color.
A component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list which appears at the user's request. If you make the combo box editable then the combo box includes an editable field into which the user can type a value.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JComboBoxkey assignments.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.beanspackage. Please see java.beans.XMLEncoderSee How to Use Combo Boxes in The Java Tutorial for further information.
@see ComboBoxModel @see DefaultComboBoxModel @beaninfo attribute: isContainer false description: A combination of a text field and a drop-down list. @version 1.
113 01114 02/2812/02 @author Arnaud Weber @author Mark Davidson
Class JComponent, void enable()Overridden@deprecatedto ensureAs ofAccessibilityJDKsupport.versionPlease1.1usereplaced{@alinkbyjava.awt.Component.setEnable(boolean).}
Class JComponent, TransferHandler getTransferHandler()Overridden@deprecatedto ensureAs ofAccessibilityJDKsupport.versionPlease1.1usereplaced{@alinkbyjava.awt.Component.setEnable(boolean).}
Gets theClass JComponent, boolean isMaximumSizeSet()transferHandlerproperty. @return the value of thetransferHandlerproperty @see TransferHandler @see #setTransferHandler @since 1.4
Returns true if the maximum size has been set to a non-Class JComponent, boolean isMinimumSizeSet()nullvalue otherwise returns false. @return true ifmaximumSizeis non-nullfalse otherwise @since 1.3
Returns true if the minimum size has been set to a non-Class JComponent, boolean isPreferredSizeSet()nullvalue otherwise returns false. @return true ifminimumSizeis non-nullfalse otherwise @since 1.3
Returns true if the preferred size has been set to a non-Class JComponent, void setTransferHandler(TransferHandler)nullvalue otherwise returns false. @return true ifpreferredSizeis non-nullfalse otherwise @since 1.3
Sets thetransferHandlerproperty which isnullif the component does not support data transfer operations.If
newHandleris not null and the system propertysuppressSwingDropSupportis not true this will install aDropTargeton theJComponent. The default for the system property is false so that aDropTargetwill be added. @param newHandler mechanism for transfer of data to and from the component @see TransferHandler @see #getTransferHandler @since 1.4 @beaninfo bound: true hidden: true description: Mechanism for transfer of data to and from the component
The main class for creating a dialog window. You can use this class to create a custom dialog or invoke the many class methods in JOptionPane to create a variety of standard dialogs. For information about creating dialogs see The Java Tutorial section How to Make Dialogs.Class JDialog, void setContentPane(Container)The
JDialogcomponent contains aJRootPaneas its only child. ThecontentPaneshould be the parent of any children of theJDialog. From the olderjava.awt.Windowobject you would normally do something like this:dialog.add(child);UsingJDialogthe proper semantic is:dialog.getContentPane().add(child);The same principle holds true for setting layout managers removing components listing children etc. All these methods should normally be sent to thecontentPaneinstead of to theJDialog. ThecontentPaneis always non-null. Attempting to set it tonullgenerates an exception. The defaultcontentPanehas aBorderLayoutmanager set on it.Please see the
JRootPanedocumentation for a complete description of thecontentPaneglassPaneandlayeredPanecomponents.In a multi-screen environment you can create a
JDialogon a different screen device than its owner. See java.awt.Frame for more information.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JDialogkey assignments.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.beanspackage. Please see java.beans.XMLEncoder @see JOptionPane @see JRootPane @beaninfo attribute: isContainer true attribute: containerDelegate getContentPane description: A toplevel window for creating dialog boxes. @version 1.666812/03/0120/02 @author David Kloba @author James Gosling @author Scott Violet
Sets theClass JDialog, void setDefaultLookAndFeelDecorated(boolean)contentPaneproperty. This method is called by the constructor.Swing's painting architecture requires an opaque
JComponentin 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 opaqueJComponent. @see JRootPane @param contentPane thecontentPaneobject for this dialog @exception java.awt.IllegalComponentStateException (a runtime exception) if the content pane parameter isnull@see #getContentPane @see RootPaneContainer#setContentPane @beaninfo hidden: true description: The client area of the dialog where child components are normally inserted.
Provides a hint as to whether or not newly createdJDialogs should have their Window decorations (such as borders widgets to close the window title...) provided by the current look and feel. IfdefaultLookAndFeelDecoratedis true the currentLookAndFeelsupports providing window decorations and the current window manager supports undecorated windows then newly createdJDialogs will have their Window decorations provided by the currentLookAndFeel. Otherwise newly createdJDialogs will have their Window decorations provided by the current window manager.You can get the same effect on a single JDialog by doing the following:
JDialog dialog = new JDialog(); dialog.setUndecorated(true); dialog.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);@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
A text component to edit various kinds of content. You can find how-to information and examples of using editor panes in Using Text Components a section in The Java Tutorial.This component uses implementations of the
EditorKitto accomplish its behavior. It effectively morphs into the proper kind of text editor for the kind of content it is given. The content type that editor is bound to at any given time is determined by theEditorKitcurrently installed. If the content is set to a new URL its type is used to determine theEditorKitthat should be used to load the content.By default the following types of content are known:
- text/plain
- Plain text which is the default the type given isn't recognized. The kit used in this case is an extension of
DefaultEditorKitthat produces a wrapped plain text view.- text/html
- HTML text. The kit used in this case is the class
javax.swing.text.html.HTMLEditorKitwhich provides HTML 3.2 support.- text/rtf
- RTF text. The kit used in this case is the class
javax.swing.text.rtf.RTFEditorKitwhich provides a limited support of the Rich Text Format.There are several ways to load content into this component.
- The setText method can be used to initialize the component from a string. In this case the current
EditorKitwill be used and the content type will be expected to be of this type.- The read method can be used to initialize the component from a
Reader. Note that if the content type is HTML relative references (e.g. for things like images) can't be resolved unless the <base> tag is used or the Base property onHTMLDocumentis set. In this case the currentEditorKitwill be used and the content type will be expected to be of this type.- The setPage method can be used to initialize the component from a URL. In this case the content type will be determined from the URL and the registered
EditorKitfor that content type will be set.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JEditorPanekey assignments.Some kinds of content may provide hyperlink support by generating hyperlink events. The HTML
EditorKitwill generate hyperlink events if theJEditorPaneis not editable (JEditorPane.setEditable(false);has been called). If HTML frames are embedded in the document the typical response would be to change a portion of the current document. The following code fragment is a possible hyperlink listener implementation that treats HTML frame events specially and simply displays any other activated hyperlinks.class Hyperactive implements HyperlinkListener { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { JEditorPane pane = (JEditorPane) e.getSource(); if (e instanceof HTMLFrameHyperlinkEvent) { HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e; HTMLDocument doc = (HTMLDocument)pane.getDocument(); doc.processHTMLFrameHyperlinkEvent(evt); } else { try { pane.setPage(e.getURL()); } catch (Throwable t) { t.printStackTrace(); } } } } }Culturally dependent information in some documents is handled through a mechanism called character encoding. Character encoding is an unambiguous mapping of the members of a character set (letters ideographs digits symbols or control functions) to specific numeric code values. It represents the way the file is stored. Example character encodings are ISO-8859-1 ISO-8859-5 Shift-jis Euc-jp and UTF-8. When the file is passed to an user agent (
JEditorPane) it is converted to the document character set (ISO-10646 aka Unicode).There are multiple ways to get a character set mapping to happen with
JEditorPane.
- One way is to specify the character set as a parameter of the MIME type. This will be established by a call to the setContentType method. If the content is loaded by the setPage method the content type will have been set according to the specification of the URL. It the file is loaded directly the content type would be expected to have been set prior to loading.
- Another way the character set can be specified is in the document itself. This requires reading the document prior to determining the character set that is desired. To handle this it is expected that the
EditorKit.read operation throw aChangedCharSetExceptionwhich will be caught. The read is then restarted with a new Reader that uses the character set specified in theChangedCharSetException(which is anIOException).
Newlines For a discussion on how newlines are handled see DefaultEditorKit. 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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A text component to edit various types of content. @author Timothy Prinzing @version 1.113 12115 04/03/0102
Class JFileChooser, FileFilter getAcceptAllFileFilter()JFileChooserprovides a simple mechanism for the user to choose a file. For information about usingJFileChoosersee How to Use File Choosers a section in The Java Tutorial.The following code pops up a file chooser for the user's home directory that sees only .jpg and .gif images:
JFileChooser chooser = new JFileChooser(); // Note: source for ExampleFileFilter can be found in FileChooserDemo // under the demo/jfc directory in the Java 2 SDK Standard Edition. ExampleFileFilter filter = new ExampleFileFilter(); filter.addExtension("jpg"); filter.addExtension("gif"); filter.setDescription("JPG & GIF Images"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(parent); if(returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); }@beaninfo attribute: isContainer false description: A component which allows for the interactive selection of a file. @version 1.92 1296 04/0311/0102 @author Jeff Dinkins
Returns theClass JFileChooser, void setMultiSelectionEnabled(boolean)AcceptAllfile filter. For example onWin32Microsoft Windows this would be All Files (*.*).
Sets the file chooser to allow multiple file selections.NOTE: this functionality@paramis not yet implemented in the currentb true if multiple files may beL&Fs.selected @beaninfo bound: true description: Sets multiple file selection mode. @see #isMultiSelectionEnabled
JFormattedTextFieldextendsJTextFieldadding support for formatting arbitrary values as well as retrieving a particular object once the user has edited the text. The following illustrates configuring aJFormattedTextFieldto edit dates:JFormattedTextField ftf = new JFormattedTextField(); ftf.setValue(new Date());Once a
JFormattedTextFieldhas been created you can listen for editing changes by way of adding aPropertyChangeListenerand listening forPropertyChangeEvents with the property namevalue.
JFormattedTextFieldallows configuring what action should be taken when focus is lost. The possible configurations are:The default is
JFormattedTextField.REVERT Revert the display to match that of getValuepossibly losing the current edit.JFormattedTextField.COMMIT Commits the current value. If the value being edited isn't considered a legal value by the AbstractFormatterthat is aParseExceptionis thrown then the value will not change and then edited value will persist.JFormattedTextField.COMMIT_OR_REVERT Similar to COMMITbut if the value isn't legal behave likeREVERT.JFormattedTextField.PERSIST Do nothing don't obtain a new AbstractFormatterand don't update the value.JFormattedTextField.COMMIT_OR_REVERTrefer to #setFocusLostBehavior for more information on this.
JFormattedTextFieldallows the focus to leave even if the currently edited value is invalid. To lock the focus down while theJFormattedTextFieldis an invalid edit state you can attach anInputVerifier. The following code snippet shows a potential implementation of such anInputVerifier:public class FormattedTextFieldVerifier extends InputVerifier { public boolean verify(JComponent input) { if (input instanceof JFormattedTextField) { JFormattedTextField ftf = (JFormattedTextField)input; AbstractFormatter formatter = ftf.getFormatter(); if (formatter = null) { String text = ftf.getText(); try { formatter.stringToValue(text); return true; } catch (ParseException pe) { return false; } } } return true; } public boolean shouldYieldFocus(JComponent input) { return verify(input); } }Alternatively you could invoke
commitEditwhich would also commit the value.
JFormattedTextFielddoes not do the formatting it self rather formatting is done through an instance ofJFormattedTextField.AbstractFormatterwhich is obtained from an instance ofJFormattedTextField.AbstractFormatterFactory. Instances ofJFormattedTextField.AbstractFormatterare notified when they become active by way of theinstallmethod at which point theJFormattedTextField.AbstractFormattercan install whatever it needs to typically aDocumentFilter. Similarly whenJFormattedTextFieldno longer needs theAbstractFormatterit will invokeuninstall.
JFormattedTextFieldtypically queries theAbstractFormatterFactoryfor anAbstractFormatwhen it gains or loses focus. Although this can change based on the focus lost policy. If the focus lost policy isJFormattedTextField.PERSISTand theJFormattedTextFieldhas been edited theAbstractFormatterFactorywill not be queried until the value has been commited. Similarly if the focus lost policy isJFormattedTextField.COMMITand an exception is thrown fromstringToValuetheAbstractFormatterFactorywill not be querired when focus is lost or gained.
JFormattedTextField.AbstractFormatteris also responsible for determining when values are commited to theJFormattedTextField. SomeJFormattedTextField.AbstractFormatters will make new values available on every edit and others will never commit the value. You can force the current value to be obtained from the currentJFormattedTextField.AbstractFormatterby way of invokingcommitEdit.commitEditwill be invoked whenever return is pressed in theJFormattedTextField.If an
AbstractFormatterFactoryhas not been explicitly set one will be set based on theClassof the value type aftersetValuehas been invoked (assuming value is non-null). For example in the following code an appropriateAbstractFormatterFactoryandAbstractFormatterwill be created to handle formatting of numbers:JFormattedTextField tf = new JFormattedTextField(); tf.setValue(new Number(100));Warning: As the
AbstractFormatterwill typically install aDocumentFilteron theDocumentand aNavigationFilteron theJFormattedTextFieldyou should not install your own. If you do you are likely to see odd behavior in that the editing policy of theAbstractFormatterwill not be enforced.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.beanspackage. Please see java.beans.XMLEncoder @version 1.12 1213 02/0311/0102 @since 1.4
An extended version ofClass JFrame, void setContentPane(Container)java.awt.Framethat adds support for the JFC/Swing component architecture. You can find task-oriented documentation about usingJFramein The Java Tutorial in the section How to Make Frames.The
JFrameclass is slightly incompatible withFrame. Like all other JFC/Swing top-level containers aJFramecontains aJRootPaneas its only child. The content pane provided by the root pane should as a rule contain all the non-menu components displayed by theJFrame. This is different from the AWTFramecase. For example to add a child to an AWT frame you'd write:frame.add(child);However usingJFrameyou need to add the child to theJFrame'scontent pane instead:frame.getContentPane().add(child);The same is true for setting layout managers removing components listing children and so on. All these methods should normally be sent to the content pane instead of the JFrame itself. 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.Unlike a
FrameaJFramehas 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 #setDefaultCloseOperation To make theJFramebehave the same as aFrameinstance usesetDefaultCloseOperation(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
JFrameon a different screen device. See java.awt.Frame for more information.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JFramekey assignments.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.beanspackage. Please see java.beans.XMLEncoder @see JRootPane @see #setDefaultCloseOperation @see java.awt.event.WindowListener#windowClosing @beaninfo attribute: isContainer true attribute: containerDelegate getContentPane description: A toplevel window which can be minimized to an icon. @version 1.90 1293 04/0318/0102 @author Jeff Dinkins @author Georges Saab @author David Kloba
Sets theClass JFrame, void setDefaultCloseOperation(int)contentPaneproperty. This method is called by the constructor.Swing's painting architecture requires an opaque
JComponentin 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 opaqueJComponent. @param contentPane thecontentPaneobject for this frame @exception java.awt.IllegalComponentStateException (a runtime exception) if the content pane parameter isnull@see #getContentPane @see RootPaneContainer#setContentPane @see JRootPane @beaninfo hidden: true description: The client area of the frame where child components are normally inserted.
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:Class JFrame, void setDefaultLookAndFeelDecorated(boolean)
DO_NOTHING_ON_CLOSE(defined inWindowConstants): Don't do anything; require the program to handle the operation in thewindowClosingmethod of a registeredWindowListenerobject.HIDE_ON_CLOSE(defined inWindowConstants): Automatically hide the frame after invoking any registeredWindowListenerobjects.DISPOSE_ON_CLOSE(defined inWindowConstants): Automatically hide and dispose the frame after invoking any registeredWindowListenerobjects.EXIT_ON_CLOSE(defined inJFrame): Exit the application using theSystemexitmethod. Use this only in applications.The value is set to
HIDE_ON_CLOSEby default. @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 invokeSystem.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.
Provides a hint as to whether or not newly createdJFrames should have their Window decorations (such as borders widgets to close the window title...) provided by the current look and feel. IfdefaultLookAndFeelDecoratedis true the currentLookAndFeelsupports providing window decorations and the current window manager supports undecorated windows then newly createdJFrames will have their Window decorations provided by the currentLookAndFeel. Otherwise newly createdJFrames 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
A lightweight object that provides many of the features of a native frame including dragging closing becoming an icon resizing title display and support for a menu bar. For task-oriented documentation and examples of using internal frames see How to Use Internal Frames a section in The Java Tutorial.Class JInternalFrame, void pack()Generally you add
JInternalFrames to aJDesktopPane. The UI delegates the look-and-feel-specific actions to theDesktopManagerobject maintained by theJDesktopPane.The
JInternalFramecontent pane is where you add child components. So to create aJInternalFramethat has a number of buttons arranged with the content pane's defaultBorderLayoutobject you might do something like this:JComponent c = (JComponent) internalFrame.getContentPane(); c.add(new JButton() BorderLayout.NORTH); c.add(new JButton() BorderLayout.CENTER);The content pane is actually managed by an instance ofJRootPanewhich also manages a layout pane glass pane and optional menu bar for the internal frame. Please see theJRootPanedocumentation for a complete description of these components.For the keyboard keys used by this component in the standard look and feel renditions see the
JInternalFramekey assignments.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.beanspackage. Please see java.beans.XMLEncoder @see InternalFrameEvent @see JDesktopPane @see DesktopManager @see JInternalFrame.JDesktopIcon @see JRootPane @version 1.135137 12/0310/01 @author David Kloba @author Rich Schiavi @beaninfo attribute: isContainer true attribute: containerDelegate getContentPane description: A frame container which is contained within another window.
Causes subcomponents of this JInternalFrame to be laid out at their preferred size. Internal frames that are iconized or maximized are first restored and then packed. If the internal frame is unable to be restored its state is not changed and will not be packed. @see java.awt.Window#pack
A display area for a short text string or an image or both. A label does not react to input events. As a result it cannot get the keyboard focus. A label can however display a keyboard alternative as a convenience for a nearby component that has a keyboard alternative but can't display it.A
JLabelobject can display either text an image or both. You can specify where in the label's display area the label's contents are aligned by setting the vertical and horizontal alignment. By default labels are vertically centered in their display area. Text-only labels are leading edge aligned by default; image-only labels are horizontally centered by default.You can also specify the position of the text relative to the image. By default text is on the trailing edge of the image with the text and image vertically aligned.
A label's leading and trailing edge are determined from the value of its java.awt.ComponentOrientation property. At present the default ComponentOrientation setting maps the leading edge to left and the trailing edge to right.
Finally you can use the
setIconTextGapmethod to specify how many pixels should appear between the text and the image. The default is 4 pixels.See How to Use Labels in The Java Tutorial for further documentation.
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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component that displays a short string and an icon. @version 1.110 12111 04/0312/0102 @author Hans Muller
A component that allows the user to select one or more objects from a list. A separate modelClass JList, void addListSelectionListener(ListSelectionListener)ListModelrepresents the contents of the list. It's easy to display an array or vector of objects using aJListconstructor that builds aListModelinstance for you:// Create a JList that displays the strings in data[] String[] data = {"one" "two" "three" "four"}; JList dataList = new JList(data); // The value of the JList model property is an object that provides // a read-only view of the data. It was constructed automatically. for(int i = 0; i
JListdoesn't support scrolling directly. To create a scrolling list you make theJListthe viewport view of aJScrollPane. For example:JScrollPane scrollPane = new JScrollPane(dataList); // Or in two steps: JScrollPane scrollPane = new JScrollPane(); scrollPane.getViewport().setView(dataList);By default the
JListselection model allows any combination of items to be selected at a time using the constantMULTIPLE_INTERVAL_SELECTION. The selection state is actually managed by a separate delegate object an instance ofListSelectionModel. HoweverJListprovides convenient properties for managing the selection.String[] data = {"one" "two" "three" "four"}; JList dataList = new JList(data); dataList.setSelectedIndex(1); // select "two" dataList.getSelectedValue(); // returns "two"The contents of a
JListcan be dynamic in other words the list elements can change value and the size of the list can change after theJListhas been created. TheJListobserves changes in its model with aswing.event.ListDataListenerimplementation. A correct implementation ofListModelnotifies it's listeners each time a change occurs. The changes are characterized by aswing.event.ListDataEventwhich identifies the range of list indices that have been modified added or removed. Simple dynamic-contentJListapplications can use theDefaultListModelclass to store list elements. This class implements theListModelinterface and provides thejava.util.VectorAPI as well. Applications that need to provide customListModelimplementations can subclassAbstractListModelwhich provides basicListDataListenersupport. For example:// This list model has about 2^16 elements. Enjoy scrolling. ListModel bigData = new AbstractListModel() { public int getSize() { return Short.MAX_VALUE; } public Object getElementAt(int index) { return "Index " + index; } }; JList bigDataList = new JList(bigData); // We don't want the JList implementation to compute the width // or height of all of the list cells so we give it a string // that's as big as we'll need for any cell. It uses this to // compute values for the fixedCellWidth and fixedCellHeight // properties. bigDataList.setPrototypeCellValue("Index 1234567890");
JListuses ajava.awt.Componentprovided by a delegate called thecellRenderererto paint the visible cells in the list. The cell renderer component is used like a "rubber stamp" to paint each visible row. Each time theJListneeds to paint a cell it asks the cell renderer for the component moves it into place usingsetBounds()and then draws it by calling its paint method. The default cell renderer uses aJLabelcomponent to render the string value of each component. You can substitute your own cell renderer using code like this:// Display an icon and a string for each object in the list. class MyCellRenderer extends JLabel implements ListCellRenderer { final static ImageIcon longIcon = new ImageIcon("long.gif"); final static ImageIcon shortIcon = new ImageIcon("short.gif"); // This is the only method defined by ListCellRenderer. // We just reconfigure the JLabel each time we're called. public Component getListCellRendererComponent( JList list Object value // value to display int index // cell index boolean isSelected // is the cell selected boolean cellHasFocus) // the list and the cell have the focus { String s = value.toString(); setText(s); setIcon((s.length() > 10) longIcon : shortIcon); if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setEnabled(list.isEnabled()); setFont(list.getFont()); setOpaque(true); return this; } } String[] data = {"one" "two" "three" "four"}; JList dataList = new JList(data); dataList.setCellRenderer(new MyCellRenderer());
JListdoesn't provide any special support for handling double or triple (or N) mouse clicks however it's easy to handle them using aMouseListener. Use theJListmethodlocationToIndex()to determine what cell was clicked. For example:final JList list = new JList(dataModel); MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = list.locationToIndex(e.getPoint()); System.out.println("Double clicked on Item " + index); } } }; list.addMouseListener(mouseListener);Note that in this example thedataListisfinalbecause it's referred to by the anonymousMouseListenerclass.For the keyboard keys used by this component in the standard look and feel (L&F) renditions see the
JListkey assignments.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.beanspackage. Please see java.beans.XMLEncoderSee How to Use Lists in The Java Tutorial for further documentation. Also see the article Advanced JList Programming in The Swing Connection.
@see ListModel @see AbstractListModel @see DefaultListModel @see ListSelectionModel @see DefaultListSelectionModel @see ListCellRenderer @beaninfo attribute: isContainer false description: A component which allows for the selection of one or more objects from a list. @version 1.
101 12103 02/0311/0102 @author Hans Muller
Adds a listener to the list that's notified each time a change to the selection occurs. Listeners added directly to theClass JList, ListSelectionListener[] getListSelectionListeners()JListwill have theirListSelectionEvent.getSource() == this JList(instead of theListSelectionModel). @param listener theListSelectionListenerto add @see #getSelectionModel @see #getListSelectionListeners
Returns an array of all theListSelectionListeners added to this JList with addListSelectionListener(). @return all of theListSelectionListeners added or an empty array if no listeners have been added @see #addListSelectionListener @since 1.4
An implementation of a menu -- a popup window containingJMenuItems that is displayed when the user selects an item on theJMenuBar. In addition toJMenuItems aJMenucan also containJSeparators.In essence a menu is a button with an associated
JPopupMenu. When the "button" is pressed theJPopupMenuappears. If the "button" is on theJMenuBarthe menu is a top-level window. If the "button" is another menu item then theJPopupMenuis "pull-right" menu.For information and examples of using menus see How to Use Menus a section in The Java Tutorial. For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JMenukey assignments.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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer true description: A popup window containing menu items displayed in a menu bar. @version 1.164 12166 04/0318/0102 @author Georges Saab @author David Karlton @author Arnaud Weber @see JMenuItem @see JSeparator @see JMenuBar @see JPopupMenu
An implementation of an item in a menu. A menu item is essentially a button sitting in a list. When the user selects the "button" the action associated with the menu item is performed. AJMenuItemcontained in aJPopupMenuperforms exactly that function.For further documentation and for examples see How to Use Menus in The Java Tutorial. For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JMenuItemkey assignments.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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: An item which can be selected in a menu. @version 1.106 12107 02/0311/0102 @author Georges Saab @author David Karlton @see JPopupMenu @see JMenu @see JCheckBoxMenuItem @see JRadioButtonMenuItem
An implementation of a popup menu -- a small window that pops up and displays a series of choices. AClass JPopupMenu, void setLightWeightPopupEnabled(boolean)JPopupMenuis used for the menu that appears when the user selects an item on the menu bar. It is also used for "pull-right" menu that appears when the selects a menu item that activates it. Finally aJPopupMenucan also be used anywhere else you want a menu to appear. For example when the user right-clicks in a specified area.For information and examples of using popup menus see How to Use Menus in The Java Tutorial. For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JPopupMenukey assignments.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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A small window that pops up and displays a series of choices. @version 1.16917612/05/0107/02 @author Georges Saab @author David Karlton @author Arnaud Weber
Sets the value of thelightWeightPopupEnabledproperty which by default istrue. By default when a look and feel displays a popup it can choose to use a lightweight (all-Java) popup. Lightweight popup windows are more efficient than heavyweight (native peer) windows but lightweight and heavyweight components do not mix well in a GUI. If your application mixes lightweight and heavyweight components you should disable lightweight popups. Some look and feels might always use heavyweight popups no matter what the value of this property. @param aFlagfalseto disable lightweight popups @beaninfo description: Determines whether lightweight popups are used when possible expert: true @see #isLightWeightPopupEnabled
A component that by default displays an integer value within a bounded interval. A progress bar typically communicates the progress of some work by displaying its percentage of completion and possibly a textual display of this percentage.Class JProgressBar, void setIndeterminate(boolean)To indicate that a task of unknown length is executing you can put a progress bar into indeterminate mode. While the bar is in indeterminate mode it animates constantly to show that work is occurring. As soon as you can determine the task's length and amount of progress you should update the progress bar's value and switch it back to determinate mode.
Here is an example of creating a progress bar where
taskis an object that returns information about the progress of some work:progressBar = new JProgressBar(0 task.getLengthOfTask()); progressBar.setValue(0); progressBar.setStringPainted(true);Here is an example of updating the value of the progress bar:progressBar.setValue(task.getCurrent());Here is an example of putting a progress bar into indeterminate mode and then switching back to determinate mode once the length of the task is known:progressBar = new JProgressBar(); ...//when the task of (initially) unknown length begins: progressBar.setIndeterminate(true); ...//do some work; get length of task... progressBar.setMaximum(newLength); progressBar.setValue(newValue); progressBar.setIndeterminate(false);For complete examples and further documentation see How to Monitor Progress a section in The Java Tutorial.
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.beanspackage. Please see java.beans.XMLEncoder @see javax.swing.plaf.basic.BasicProgressBarUI @beaninfo attribute: isContainer false description: A component that displays an integer value. @version 1.899012/03/0112/02 @author Michael C. Albers @author Kathy Walrath
Sets theindeterminateproperty of the progress bar which determines whether the progress bar is in determinate or indeterminate mode.By default the progress bar is determinate and this method returns false.An indeterminate progress bar continuously displays animation indicating that an operation of unknown length is occurring. By default this property isfalse. Some look and feels might not support indeterminate progress bars; they will ignore this property.See How to Monitor Progress for examples of using indeterminate progress bars. @param newValue
trueif the progress bar should change to indeterminate mode;falseif it should revert to normal. @see #isIndeterminate @see javax.swing.plaf.basic.BasicProgressBarUI @since 1.4 @beaninfo bound: true attribute: visualUpdate true description: Set whether the progress bar is indeterminate (true) or normal (false).
A lightweight container used behind the scenes byClass JRootPane, void setContentPane(Container)JFrameJDialogJWindowJAppletandJInternalFrame. For task-oriented information on functionality provided by root panes see How to Use Root Panes a section in The Java Tutorial.The following image shows the relationships between the classes that use root panes.
The "heavyweight" components (those that delegate to a peer or native component on the host system) are shown with a darker heavier box. The four heavyweight JFC/Swing containers (
JFrameJDialogJWindowandJApplet) are shown in relation to the AWT classes they extend. These four components are the only heavyweight containers in the Swing library. The lightweight containeris also shown. All five of these JFC/Swing containers implement theJRootPaneJInternalPaneRootPaneContainerinterface and they all delegate their operations to aJRootPane(shown with a little "handle" on top).Note: TheJComponentmethodgetRootPanecan be used to obtain theJRootPanethat contains a given component.The diagram at right shows the structure of a
![]()
JRootPane. AJRootpaneis made up of aglassPanean optionalmenuBarand acontentPane. (TheJLayeredPanemanages themenuBarand thecontentPane.) TheglassPanesits over the top of everything where it is in a position to intercept mouse movements. Since theglassPane(like thecontentPane) can be an arbitrary component it is also possible to set up theglassPanefor drawing. Lines and images on theglassPanecan then range over the frames underneath without being limited by their boundaries.Although the
menuBarcomponent is optional thelayeredPanecontentPaneandglassPanealways exist. Attempting to set them tonullgenerates an exception.To add components to the
JRootPane(other than the optional menu bar) you add the object to thecontentPaneof theJRootPanelike this:rootPane.getContentPane().add(child);The same principle holds true for setting layout managers removing components listing children etc. All these methods are invoked on thecontentPaneinstead of on theJRootPane.Note: The default layout manager for theIf acontentPaneis aBorderLayoutmanager. However theJRootPaneuses a customLayoutManager. So when you want to change the layout manager for the components you added to aJRootPanebe sure to use code like this:rootPane.getContentPane().setLayout(new BoxLayout());JMenuBarcomponent is set on theJRootPaneit is positioned along the upper edge of the frame. ThecontentPaneis adjusted in location and size to fill the remaining area. (TheJMenuBarand thecontentPaneare added to thelayeredPanecomponent at theJLayeredPane.FRAME_CONTENT_LAYERlayer.)The
layeredPaneis the parent of all children in theJRootPane-- both as the direct parent of the menu and the grandparent of all components added to thecontentPane. It is an instance ofJLayeredPanewhich provides the ability to add components at several layers. This capability is very useful when working with menu popups dialog boxes and dragging -- situations in which you need to place a component on top of all other components in the pane.The
glassPanesits on top of all other components in theJRootPane. That provides a convenient place to draw above all other components and makes it possible to intercept mouse events which is useful both for dragging and for drawing. Developers can usesetVisibleon theglassPaneto control when theglassPanedisplays over the other children. By default theglassPaneis not visible.The custom
LayoutManagerused byJRootPaneensures that:Any other views in the
- The
glassPanefills the entire viewable area of theJRootPane(bounds - insets).- The
layeredPanefills the entire viewable area of theJRootPane. (bounds - insets)- The
menuBaris positioned at the upper edge of thelayeredPane.- The
contentPanefills the entire viewable area minus themenuBarif present.JRootPaneview hierarchy are ignored.If you replace the
LayoutManagerof theJRootPaneyou are responsible for managing all of these views. So ordinarily you will want to be sure that you change the layout manager for thecontentPanerather than for theJRootPaneitselfThe painting architecture of Swing requires an opaque
JComponentto exist in the containment hieararchy above all other components. This is typically provided by way of the content pane. If you replace the content pane it is recommended that you make the content pane opaque by way ofsetOpaque(true). Additionally if the content pane overridespaintComponentit will need to completely fill in the background in an opaque color inpaintComponent.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.beanspackage. Please see java.beans.XMLEncoder @see JLayeredPane @see JMenuBar @see JWindow @see JFrame @see JDialog @see JApplet @see JInternalFrame @see JComponent @see BoxLayout @see Mixing Heavy and Light Components @version 1.778012/03/0120/02 @author David Kloba
Sets the content pane -- the container that holds the components parented by the root pane.Swing's painting architecture requires an opaque
JComponentin 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 opaqueJComponent. @param content theContainerto use for component-contents @exception java.awt.IllegalComponentStateException (a runtime exception) if the content pane parameter isnull
A single line input field that lets the user select a number or an object value from an ordered sequence. Spinners typically provide a pair of tiny arrow buttons for stepping through the elements of the sequence. The keyboard up/down arrow keys also cycle through the elements. The user may also be allowed to type a (legal) value directly into the spinner. Although combo boxes provide similar functionality spinners are sometimes preferred because they don't require a drop down list that can obscure important data.Class JSpinner, JComponent createEditor(SpinnerModel)A
JSpinner's sequence value is defined by itsSpinnerModel. Themodelcan be specified as a constructor argument and changed with themodelproperty.SpinnerModelclasses for some common types are provided:SpinnerListModelSpinnerNumberModelandSpinnerDateModel.A
JSpinnerhas a single child component that's responsible for displaying and potentially changing the current element or value of the model which is called theeditor. The editor is created by theJSpinner's constructor and can be changed with theeditorproperty. TheJSpinner's editor stays in sync with the model by listening forChangeEvents.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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A single line input field that lets the user select a number or an object value from an ordered set. @see SpinnerModel @see AbstractSpinnerModel @see SpinnerListModel @see SpinnerNumberModel @see SpinnerDateModel @see JFormattedTextField @version 1.22 1226 04/0318/0102 @author Hans Muller @since 1.4
This method is called by the constructors to create theClass JSpinner, void fireStateChanged()JComponentthat displays the current value of the sequence. The editor may also allow the user to enter an element of the sequence directly. An editor must listen forChangeEventson themodeland keep the value it displays in sync with the value of the model.Subclasses may override this method to add support for new
SpinnerModelclasses. Alternatively one can just replace the editor created here with thesetEditormethod. The default mapping from model type to editor is:@return a component that displays the current value of the sequence @param model the value of getModel @see #getModel @see #setEditor
SpinnerNumberModel =<gt; JSpinner.NumberEditorSpinnerDateModel =<gt; JSpinner.DateEditorSpinnerListModel =<gt; JSpinner.ListEditor- all others =&
ltgt;JSpinner.DefaultEditor
Sends aChangeEventwhose source is thisJSpinnerto eachChangeListener. When aChangeListenerhas been added to the spinner this method method is called each time aChangeEventis received from the model. @see #addChangeListener @see #removeChangeListener @see EventListenerList
A component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon. For examples and information on using tabbed panes see How to Use Tabbed Panes a section in The Java Tutorial.Class JTabbedPane, constructor JTabbedPane()Tabs/components are added to a
TabbedPaneobject by using theaddTabandinsertTabmethods. A tab is represented by an index corresponding to the position it was added in where the first tab has an index equal to 0 and the last tab has an index equal to the tab count minus 1.The
TabbedPaneuses aSingleSelectionModelto represent the set of tab indices and the currently selected index. If the tab count is greater than 0 then there will always be a selected index which by default will be initialized to the first tab. If the tab count is 0 then the selected index will be -1.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JTabbedPanekey assignments.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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer true description: A component which provides a tab folder metaphor for displaying one component from a set of components. @version 1.124 12127 07/0322/0102 @author Dave Moore @author Philip Milne @author Amy Fowler @see SingleSelectionModel
Creates an emptyClass JTabbedPane, constructor JTabbedPane(int)TabbedPanewith a default tab placement ofJTabbedPane.TOPand default tab layout policy of JTabbedPane.WRAP_TAB_LAYOUT. @see #addTab
Creates an emptyClass JTabbedPane, void setTabLayoutPolicy(int)TabbedPanewith the specified tab placement of either:JTabbedPane.TOPJTabbedPane.BOTTOMJTabbedPane.LEFTorJTabbedPane.RIGHTand a default tab layout policy of JTabbedPane.WRAP_TAB_LAYOUT. @param tabPlacement the placement for the tabs relative to the content @see #addTab
Sets the policy which the tabbedpane will use in laying out the tabs when all the tabs will not fit within a single run. Possible values are:Class JTabbedPane, int SCROLL_TAB_LAYOUTThe default value if not set by the UI is
JTabbedPane.WRAP_TAB_LAYOUTJTabbedPane.SCROLL_TAB_LAYOUTJTabbedPane.WRAP_TAB_LAYOUT.Some look and feels might only support a subset of the possible layout policies in which case the value of this property may be ignored. @param layoutPolicy the policy used to layout the tabs @exception IllegalArgumentException if layoutPolicy value isn't one of the above valid values @see #getTabLayoutPolicy @since 1.4 @beaninfo preferred: true bound: true attribute: visualUpdate true enum: WRAP_TAB_LAYOUT JTabbedPane.WRAP_TAB_LAYOUT SCROLL_TAB_LAYOUT JTabbedPane.SCROLL_TAB_LAYOUT description: The tabbedpane's policy for laying out the tabs
TheTabtablayout policy for providing ascrollable regionsubset of available tabs when all the tabs will not fit within a single run.AIfpair ofallscroll buttons are provided for the user to controlthe tabs do not fit within a single run thescrolling. The placementlookof the scroll buttons is determined by the look and feeland feel will provide a way to navigate to hidden tabs.
TheClass JTable, Rectangle getCellRect(int, int, boolean)JTableis used to display and edit regular two-dimensional tables of cells. See How to Use Tables in The Java Tutorial for task-oriented documentation and examples of usingJTable.The
JTablehas many facilities that make it possible to customize its rendering and editing but provides defaults for these features so that simple tables can be set up easily. For example to set up a table with 10 rows and 10 columns of numbers:
TableModel dataModel = new AbstractTableModel() { public int getColumnCount() { return 10; } public int getRowCount() { return 10;} public Object getValueAt(int row int col) { return new Integer(row*col); } }; JTable table = new JTable(dataModel); JScrollPane scrollpane = new JScrollPane(table);Note that if you wish to use a
JTablein a standalone view (outside of aJScrollPane) and want the header displayed you can get it using #getTableHeader and display it separately.When designing applications that use the
JTableit is worth paying close attention to the data structures that will represent the table's data. TheDefaultTableModelis a model implementation that uses aVectorofVectors ofObjects to store the cell values. As well as copying the data from an application into theDefaultTableModelit is also possible to wrap the data in the methods of theTableModelinterface so that the data can be passed to theJTabledirectly as in the example above. This often results in more efficient applications because the model is free to choose the internal representation that best suits the data. A good rule of thumb for deciding whether to use theAbstractTableModelor theDefaultTableModelis to use theAbstractTableModelas the base class for creating subclasses and theDefaultTableModelwhen subclassing is not required.The "TableExample" directory in the demo area of the source distribution gives a number of complete examples of
JTableusage covering how theJTablecan be used to provide an editable view of data taken from a database and how to modify the columns in the display to use specialized renderers and editors.The
JTableuses integers exclusively to refer to both the rows and the columns of the model that it displays. TheJTablesimply takes a tabular range of cells and usesgetValueAt(int int)to retrieve the values from the model during painting.By default columns may be rearranged in the
JTableso that the view's columns appear in a different order to the columns in the model. This does not affect the implementation of the model at all: when the columns are reordered theJTablemaintains the new order of the columns internally and converts its column indices before querying the model.So when writing a
TableModelit is not necessary to listen for column reordering events as the model will be queried in its own coordinate system regardless of what is happening in the view. In the examples area there is a demonstration of a sorting algorithm making use of exactly this technique to interpose yet another coordinate system where the order of the rows is changed rather than the order of the columns.As for all
JComponentclasses you can use InputMap and ActionMap to associate an Action object with a KeyStroke and execute the action under specified conditions.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JTablekey assignments.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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component which displays data in a two dimensional grid. @version 1.197 12202 07/0315/0102 @author Philip Milne
Returns a rectangle for the cell that lies at the intersection ofrowandcolumn. IfincludeSpacingis true then the value returned has the full height and width of the row and column specified. If it is false the returned rectangle is inset by the intercell spacing to return the true bounds of the rendering or editing component as it will be set during rendering.If the column index is valid but the row index is less than zero the method returns a rectangle with the
yandheightvalues set appropriately and thexandwidthvalues both set to zero. In general when either the row or column indices indicate a cell outside the appropriate range the method returns a rectangle depicting the closest edge of the closest cell that is within the table's range. When both row and column indices are out of range the returned rectangle covers the closest point of the closest cell.In all cases calculations that use this method to calculate results along one axis will not fail because of anomalies in calculations along the other axis. When the cell is not valid the
includeSpacingparameter is ignored. @param row the row index where the desired cell is located @param column the column index where the desired cell is located in the display; this is not necessarily the same as the column index in the data model for the table; the #convertColumnIndexToView(int) method may be used to convert a data model column index to a display column index @param includeSpacing if false return the true cell bounds - computed by subtracting the intercell spacing from the height and widths of the column and row models @return the rectangle containing the cell at locationrowcolumn
AJTextAreais a multi-line area that displays plain text. It is intended to be a lightweight component that provides source compatibility with thejava.awt.TextAreaclass where it can reasonably do so. You can find information and examples of using all the text components in Using Text Components a section in The Java Tutorial.This component has capabilities not found in the
java.awt.TextAreaclass. The superclass should be consulted for additional capabilities. Alternative multi-line text classes with more capabilities areJTextPaneandJEditorPane.The
java.awt.TextAreainternally handles scrolling.JTextAreais different in that it doesn't manage scrolling but implements the swingScrollableinterface. This allows it to be placed inside aJScrollPaneif scrolling behavior is desired and used directly if scrolling is not desired.The
java.awt.TextAreahas the ability to do line wrapping. This was controlled by the horizontal scrolling policy. Since scrolling is not done byJTextAreadirectly backward compatibility must be provided another way.JTextAreahas a bound property for line wrapping that controls whether or not it will wrap lines. By default the line wrapping property is set to false (not wrapped).
java.awt.TextAreahas two propertiesrowsandcolumnsthat are used to determine the preferred size.JTextAreauses these properties to indicate the preferred size of the viewport when placed inside aJScrollPaneto match the functionality provided byjava.awt.TextArea.JTextAreahas a preferred size of what is needed to display all of the text so that it functions properly inside of aJScrollPane. If the value forrowsorcolumnsis equal to zero the preferred size along that axis is used for the viewport preferred size along the same axis.The
java.awt.TextAreacould be monitored for changes by adding aTextListenerforTextEvents. In theJTextComponentbased components changes are broadcasted from the model via aDocumentEventtoDocumentListeners. TheDocumentEventgives the location of the change and the kind of change if desired. The code fragment might look something like:DocumentListener myListener = ; JTextArea myArea = ; myArea.getDocument().addDocumentListener(myListener);For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JTextAreakey assignments.
Newlines For a discussion on how newlines are handled see DefaultEditorKit. 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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A multi-line area that displays plain text. @author Timothy Prinzing @version 1.83 1284 04/03/01/02 @see JTextPane @see JEditorPane
A control that displays a set of hierarchical data as an outline. You can find task-oriented documentation and examples of using trees in How to Use Trees a section in The Java Tutorial.Class JTree, void expandPath(TreePath)A specific node in a tree can be identified either by a
TreePath(an object that encapsulates a node and all of its ancestors) or by its display row where each row in the display area displays one node. An expanded node isonea non-leaf node (as identified byTreeModel.isLeaf(node)returning false) that will displays its children when all its ancestors are expanded. A collapsed node is one which hides them. A hidden node is one which is under a collapsed ancestor. All of a viewable nodes parents are expanded but may or may not be displayed. A displayed node is both viewable and in the display area where it can be seen.The following
JTreemethods use "visible" to mean "displayed":
isRootVisible()setRootVisible()scrollPathToVisible()scrollRowToVisible()getVisibleRowCount()setVisibleRowCount()The next group of
JTreemethods use "visible" to mean "viewable" (under an expanded parent):
isVisible()makeVisible()If you are interested in knowing when the selection changes implement the
TreeSelectionListenerinterface and add the instance using the methodaddTreeSelectionListener.valueChangedwill be invoked when the selection changes that is if the user clicks twice on the same nodevalueChangedwill only be invoked once.If you are interested in detecting either double-click events or when a user clicks on a node regardless of whether or not it was selected we recommend you do the following:
final JTree tree = ...; MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { int selRow = tree.getRowForLocation(e.getX() e.getY()); TreePath selPath = tree.getPathForLocation(e.getX() e.getY()); if(selRow = -1) { if(e.getClickCount() == 1) { mySingleClick(selRow selPath); } else if(e.getClickCount() == 2) { myDoubleClick(selRow selPath); } } } }; tree.addMouseListener(ml);NOTE: This example obtains both the path and row but you only need to get the one you're interested in.To use
JTreeto display compound nodes (for example nodes containing both a graphic icon and text) subclass TreeCellRenderer and use #setCellRenderer to tell the tree to use it. To edit such nodes subclass TreeCellEditor and use #setCellEditorLike all
JComponentclasses you can use InputMap and ActionMap to associate an Action object with a KeyStroke and execute the action under specified conditions.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JTreekey assignments.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.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component that displays a set of hierarchical data as an outline. @version 1.159 03161 05/0803/02 @author Rob Davis @author Ray Ryan @author Scott Violet
Ensures that the node identified by the specified path is expanded and viewable. If the last item in the path is a leaf this will have no effect. @param path the TreePath identifying a node
The "viewport" or "porthole" through which you see the underlying information. When you scroll what moves is the viewport. It is like peering through a camera's viewfinder. Moving the viewfinder upwards brings new things into view at the top of the picture and loses things that were at the bottom.By default
JViewportis opaque. To change this use thesetOpaquemethod.NOTE:We have implemented a faster scrolling algorithm that does not require a buffer to draw in. The algorithm works as follows:
In general this approach is much faster. Compared to the backing store approach this avoids the overhead of maintaining an offscreen buffer and having to do two
- The view and parent view and checked to see if they are
JComponentsif they aren't stop and repaint the whole viewport.- If the viewport is obscured by an ancestor stop and repaint the whole viewport.
- Compute the region that will become visible if it is as big as the viewport stop and repaint the whole view region.
- Obtain the ancestor
Window's graphics and do acopyAreaon the scrolled region.- Message the view to repaint the newly visible region.
- The next time paint is invoked on the viewport if the clip region is smaller than the viewport size a timer is kicked off to repaint the whole region.
copyAreas. Compared to the non backing store case this approach will greatly reduce the painted region.This approach can cause slower times than the backing store approach when the viewport is obscured by another window or partially offscreen. When another window obscures the viewport the copyArea will copy garbage and a paint event will be generated by the system to inform us we need to paint the newly exposed region. The only way to handle this is to repaint the whole viewport which can cause slower performance than the backing store case. In most applications very rarely will the user be scrolling while the viewport is obscured by another window or offscreen so this optimization is usually worth the performance hit when obscured.
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.beanspackage. Please see java.beans.XMLEncoder @version 1.10210412/03/0120/02 @author Hans Muller @author Philip Milne @see JScrollPane
Popups are used to display aComponentto the user typically on top of all the otherComponents in a particular containment hierarchy.Popups have a very small life cycle. Once you have obtained aPopupand hidden it (invoked thehidemethod) you should no longer invoke any methods on it. This allows thePopupFactoryto cachePopups for later use.The general contract is that if you need to change the size of the
Componentor location of thePopupyou should obtain a newPopup.
Popupdoes not descend fromComponentrather implementations ofPopupare responsible for creating and maintaining their ownComponents to render the requestedComponentto the user.You typically do not explicitly create an instance of
Popupinstead obtain one from aPopupFactory. @see PopupFactory @version 1.1112 04/0302/0102 @since 1.4
PopupFactoryas the name implies is used to obtain instances ofPopups.Popups are used to display aComponentabove all otherComponents in a particular containment hierarchy. The general contract is that once you have obtained aPopupfrom aPopupFactoryyou must invokehideon thePopup. The typical usage is:PopupFactory factory = PopupFactory.getSharedInstance(); Popup popup = factory.getPopup(owner contents x y); popup.show(); ... popup.hide();@see Popup @version 1.14 1215 04/0311/0102 @since 1.4
This class manages repaint requests allowing the number of repaints to be minimized for example by collapsing multiple requests into a single repaint for members of a component tree. @version 1.49 1251 04/0318/0102 @author Arnaud Weber
The layout manager used byJScrollPane.JScrollPaneLayoutis responsible for nine components: a viewport two scrollbars a row header a column header and four "corner" components.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.beanspackage. Please see java.beans.XMLEncoder @see JScrollPane @see JViewport @version 1.5455 12/0307/01 @author Hans Muller
For the convenience of layout managers calculates information about the size and position of components. All size and position calculation methods are class methods that take arrays of SizeRequirements as arguments. The SizeRequirements class supports two types of layout:
- tiled
- The components are placed end-to-end starting either at coordinate 0 (the leftmost or topmost position) or at the coordinate representing the end of the allocated span (the rightmost or bottommost position).
- aligned
- The components are aligned as specified by each component's X or Y alignment value.
Each SizeRequirements object contains information about either the width (and X alignment) or height (and Y alignment) of a single component or a group of components:
minimum- The smallest reasonable width/height of the component or component group in pixels.
preferred- The natural width/height of the component or component group in pixels.
maximum- The largest reasonable width/height of the component or component group in pixels.
alignment- The X/Y alignment of the component or component group.
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.beanspackage. Please see java.beans.XMLEncoder @see Component#getMinimumSize @see Component#getPreferredSize @see Component#getMaximumSize @see Component#getAlignmentX @see Component#getAlignmentY @version 1.29 1230 04/0317/0102