|
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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.41 0246 12/0203/0001 @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.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.133 02153 12/0903/01 @author Jeff Dinkins
This class implements accessibility support for theAbstractButtonclass. It provides an implementation of the Java Accessibility API appropriate to button and menu item user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
ExtendsChangeListenerto be serializable.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Factory method which sets theClass AbstractButton, void fireActionPerformed(ActionEvent)ActionEventsource's properties according to values from theActioninstance. The properties which are set may differ for subclasses. By default the properties which get set areText Icon Enabled ToolTipText ActionCommandandMnemonic.If the
Actionpassed in isnullthe following things will occur:@param a the
- the text is set to
null- the icon is set to
null- enabled is set to true
- the tooltip text is set to
nullActionfrom which to get the properties ornull@since 1.3 @see Action @see #setAction
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using theClass AbstractButton, void fireItemStateChanged(ItemEvent)parameters passed into the fireeventmethodparameter. @parameevent theActionEventobject @see EventListenerList
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using theClass AbstractButton, void fireStateChanged()parameters passed into the fireeventmethodparameter. @param event theItemEventobject @see EventListenerList
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily createdClass AbstractButton, Icon getDisabledSelectedIcon()using the parameters passed into the fire method. @see EventListenerList
Returns the icon used by the button when it's disabled and selected. If not no disabled selection icon has been set the button constructs one from the selection icon. <-- PENDING(jeff): the disabled selection icon really should be created (ifClass AbstractButton, int getHorizontalTextPosition()necesarynecessary) by the L&F. --> @return thedisabledSelectedIconproperty @see #getPressedIcon @see #setDisabledIcon
Returns the horizontal position of the text relative to the icon. @return theClass AbstractButton, boolean isBorderPainted()horizontalTextPositionproperty one of the following values:
- SwingConstants.RIGHT
(the default)- SwingConstants.LEFT
- SwingConstants.CENTER
- SwingConstants.LEADING
- SwingConstants.TRAILING (the default)
Class AbstractButton, boolean isContentAreaFilled()ReturnsGetswhethertheborder shouldborderPaintedbe paintedproperty. @returntrue iftheborder shouldvaluebe paintedof thefalseborderPaintedotherwiseproperty @see #setBorderPainted
Class AbstractButton, boolean isFocusPainted()ChecksGetswhether the "content area" ofthebutton should becontentAreaFilledfilledproperty. @return thecontentAreaFilledproperty @see #setFocusPaintedsetContentAreaFilled
Class AbstractButton, boolean isFocusTraversable()ReturnsGetswhether focus shouldthebepaintFocuspaintedproperty. @return thepaintFocusproperty @see #setFocusPainted
Class AbstractButton, boolean isRolloverEnabled()IdentifiesReturns whetheror notthiscomponentComponentcanreceivebecome the focus owner. @returntrueif thiscomponentComponentcanisreceivefocusable;thefalsefocusotherwise @see #setFocusable @since JDK1.1 @deprecated As of 1.4 replaced byisFocusable().
Class AbstractButton, void paintBorder(Graphics)ChecksGetswhether rollover effectsthearerolloverEnabledenabledproperty. @return the value of therolloverEnabledproperty @see #setFocusPaintedsetRolloverEnabled
Paint the button's border ifClass AbstractButton, void setBorderPainted(boolean)BorderPaintedproperty is true and the button has a border. @param g theGraphicscontext in which to paint @see #paint @see #setBorder
SetsClass AbstractButton, void setContentAreaFilled(boolean)whethertheborderPaintedproperty. Iftrueand the button has a bordershould bethe border is painted. The default value for theborderPaintedproperty istrue. @param b if true and border property is notnullthe border is painted.@see #isBorderPainted @beaninfo bound: true attribute: visualUpdate true description: Whether the border should be painted.
SetsClass AbstractButton, void setFocusPainted(boolean)whetherthecontentAreaFilledproperty. Iftruethe buttonshouldwill paint the content areaor leave it transparent. If you wish to have a transparent buttonfor example andsuch as an icon only button for example then you should set this tofalse. Do not callsetOpaque(false).Whether theThe defaultbuttonvalue forfollowsthe theRepaintManagercontentAreaFilled's concept ofopacityproperty isL&F depandanttrue.This function may cause the component's opaque property to change.
The exact behavior of calling this function varies on a component-by-component and L&F-by-L&F basis. @param b if true
rollover effectsthe content should bepaintedfilled; if false the content area is not filled @see #isContentAreaFilled @see #setOpaque @beaninfo bound: true attribute: visualUpdate true description: Whether the button should paint the content area or leave it transparent.
SetsClass AbstractButton, void setHorizontalTextPosition(int)whetherthepaintFocusproperty which must betruefor the focusshouldstate to be painted. The default value for thepaintFocusproperty istrue. Some look and feels might not paint focus state; they will ignore this property. @param b iftruethe focus stateisshould be painted @see #isFocusPainted @beaninfo bound: true attribute: visualUpdate true description: Whether focus should be painted
Sets the horizontal position of the text relative to the icon. @param textPosition one of the following values:Class AbstractButton, void setMnemonic(char)@exception IllegalArgumentException if
- SwingConstants.RIGHT
(the default)- SwingConstants.LEFT
- SwingConstants.CENTER
- SwingConstants.LEADING
- SwingConstants.TRAILING (the default)
textPositionis not one of the legal values listed above @beaninfo bound: true enum: LEFT SwingConstants.LEFT CENTER SwingConstants.CENTER RIGHT SwingConstants.RIGHT LEADING SwingConstants.LEADING TRAILING SwingConstants.TRAILING attribute: visualUpdate true description: The horizontal position of the text relative to the icon.
Class AbstractButton, void setMnemonic(int)SpecifiesThis method is now obsolete please usesetMnemonic(int)to set the mnemonicvaluefor a button. This method is only designed to handle character values which fall between 'a' and 'z' or 'A' and 'Z'. @param mnemonic a char specifying the mnemonic value @see #setMnemonic(int) @beaninfo bound: true attribute: visualUpdate true description: the keyboard character mnemonic
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.Class AbstractButton, void setRolloverEnabled(boolean)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 @beaninfo bound: true attribute: visualUpdate true description: the keyboard character mnemonic
SetsClass AbstractButton, void setUI(ButtonUI)whethertherolloverEnabledproperty which must betruefor rollover effectsshouldtobeoccur.enabledThe default value for therolloverEnabledproperty isfalse. Some look and feels might not implement rollover effects; they will ignore this property. @param b iftruerollover effects should be painted @see #isRolloverEnabled @beaninfo bound: true attribute: visualUpdate true description: Whether rollover effects should be enabled.
Sets the L&F object that renders this component. @param ui the ButtonUI L&F object @see #getUI @beaninfo bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the LookAndFeel.
Class AbstractButton, void updateUI()Class AbstractButton, String CONTENT_AREA_FILLED_CHANGED_PROPERTYNotificationResetsfromtheUIFactoryUI propertythatto a value from theL&Fcurrent lookhas changedand feel. Subtypes ofAbstractButtonshould override this to update the UI. For exampleJButtonmight do the following:setUI((ButtonUI)UIManager.getUI( "ButtonUI" "javax.swing.plaf.basic.BasicButtonUI" this));
Identifies a changeClass AbstractButton, String ROLLOVER_ENABLED_CHANGED_PROPERTYfrom rollovertoenabled to disabled or back to enabledhaving the button paint the content area.
Identifies a changein thefrom rolloverbutton'senabled to disabled or back to enabled.
@version 1.4 028 12/0203/0001 A base class forCellEditorsproviding default implementations for the methods in theCellEditorinterface exceptgetCellEditorValue(). Like the other abstract implementations in Swing also manages a list of listeners.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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @author Philip Milne
TheClass AbstractListModel, void addListDataListener(ListDataListener)Abstractabstract definition for the data modelthethat provides aListwith its contents.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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.22 0230 12/0203/0001 @author Hans Muller
Class AbstractListModel, void fireContentsChanged(Object, int, int)AddAdds a listener to the list that's notified each time a change to the data model occurs. @param l theListDataListenerto be added
Class AbstractListModel, void fireIntervalAdded(Object, int, int)AbstractListModelsubclasses must call this method after one or more elements of the list change. The changed elements are specified byathe closed interval index0 index1i.e.-- therange that includes both index0endpointsand index1are included. Note that index0 need not be less than or equal to index1. @param sourceThetheListModelthat changed typically "this".@param index0Oneone end of the new interval.@param index1Thethe other end of the new interval.@see EventListenerList @see DefaultListModel
Class AbstractListModel, void fireIntervalRemoved(Object, int, int)AbstractListModelsubclasses must call this method after one or more elements are added to the model. The new elements are specified by a closed interval index0 index1i.e.-- therange that includesenpointsboth index0 andareindex1included. Note that index0 need not be less than or equal to index1. @param sourceThetheListModelthat changed typically "this".@param index0Oneone end of the new interval.@param index1Thethe other end of the new interval.@see EventListenerList @see DefaultListModel
Class AbstractListModel, EventListener[] getListeners(Class)AbstractListModelsubclasses must call this method after one or more elements are removed from the model. The new elements are specified by a closed interval index0 index1 i.e. the range that includes both index0 and index1. Note that index0 need not be less than or equal to index1. @param sourceThethe ListModel that changed typically "this".@param index0Oneone end of the new interval.@param index1Thethe other end of the new interval.@see EventListenerList @see DefaultListModel
Class AbstractListModel, void removeListDataListener(ListDataListener)ReturnReturns an array of all the objects currently registered asFooListeners upon this model.FooListeners are registered using theaddFooListenermethod.You can specify the
listenerslistenerTypeargument with a class literal such asFooListener.class. For example you can query a list modelmfor its list dataofwith thegivenfollowingtypecode:thatListDataListener[] ldls = (ListDataListener[])(m.getListeners(ListDataListener.class));wereIfaddedno suchtolisteners exist thismodelmethod returns an empty array. @returnsparamalllistenerType the type ofthelisteners requested; this parameter should specify an interface that descends fromjava.util.EventListener@return an array of all objectsrecievingregistered aslistenerTypeFooListenersnotificationsonfromthis model or an empty array if no such listeners have been added @exception ClassCastException iflistenerTypedoesn't specify a class or interface that implementsjava.util.EventListener@see #getListDataListeners @since 1.3
RemoveRemoves a listener from the list that's notified each time a change to the data model occurs. @param l theListDataListenerto be removed
TheClass Action, String ACCELERATOR_KEYActioninterface provides a useful extension to theActionListenerinterface in cases where the same functionality may be accessed by several controls.In addition to the
actionPerformedmethod defined by theActionListenerinterface this interface allows the application to define in a single place:Certain containers including menus and tool bars know how to add an
- One or more text strings that describe the function. These strings can be used for example to display the flyover text for a button or to set the text in a menu item.
- One or more icons that depict the function. These icons can be used for the images in a menu control or for composite entries in a more sophisticated user interface.
- The enabled/disabled state of the functionality. Instead of having to separately disable the menu item and the toolbar button the application can disable the function that implements this interface. All components which are registered as listeners for the state change then know to disable event generation for that item and to modify the display accordingly.
Actionobject. When anActionobject is added to such a container the container:For example both a menu item and a toolbar button could access a
- Creates a component that is appropriate for that container (a tool bar creates a button component for example).
- Gets the appropriate property(s) from the
Actionobject to customize the component (for example the icon image and flyover text).- Checks the
intialinitial state of theActionobject to determine if it is enabled or disabled and renders the component in the appropriate fashion.- Registers a listener with the
Actionobject so that is notified of state changes. When theActionobject changes from enabled to disabled or back the container makes the appropriate revisions to the event-generation mechanisms and renders the component accordingly.Cutaction object. The text associated with the object is specified as "Cut" and an image depicting a pair of scissors is specified as its icon. TheCutaction-object can then be added to a menu and to a tool bar. Each container does the appropriate things with the object and invokes itsactionPerformedmethod when the component associated with it is activated. The application can then disable or enable the application object without worrying about what user-interface components are connected to it.This interface can be added to an existing class or used to create an adapter (typically by subclassing
AbstractActio). TheActionobject can then be added to multiple action-aware containers and connected to Action-capable components. The GUI controls can then be activated or deactivated all at once by invoking theActionobject'ssetEnabledmethod.Note that
Actionimplementations tend to be more expensive in terms of storage than a typicalActionListenerwhich does not offer the benefits of centralized control of functionality and broadcast of property changes. For th is reason you should take care to only useActions where their benefits are desired and use simpleActionListenerselsewhere. @version 1.21240212/0203/0001 @author Georges Saab @see AbstractAction
The key used for storing a KeyStroke to be used as the accelerator for the action. @since 1.3
Class Action, String MNEMONIC_KEYThe key used for storing an int key code to be used as the mnemonic for the action. @since 1.3
ActionMapprovides mappings fromObjects (called keys orActionnames) toActions. AnActionMapis usually used with anInputMapto locate a particular action when a key is pressed. As withInputMapanActionMapcan have a parent that is searched for keys not defined in theActionMap.As with
InputMapif you create a cycle eg:ActionMap am = new ActionMap(); ActionMap bm = new ActionMap(): am.setParent(bm); bm.setParent(am);some of the methods will cause a StackOverflowError to be thrown. @see InputMap @version 1.8 0211 12/0203/0001 @author Scott Violet
Factory class for vending standardClass BorderFactory, TitledBorder createTitledBorder(Border)Borderobjects. Wherever possible this factory will hand out references to sharedBorderinstances. For further information and examples see How to Use Borders a section in The Java Tutorial. @version 1.23 0225 12/0203/0001 @author David Kloba
Creates a new title border with an empty title specifying the border object using the default text position (sitting on the top line) and default justification (leading) and using the default font and text color.and@param borderdetermined bythecurrent lookBorderandobjectfeel.to(TheaddMotif and Windows look and feelsthe title to if null theuseBorderan etchedis determinedborder;byThe Javathe current look and feeluses a gray border.)@paramborder thetitle aBorderStringobject to addcontaining the text of the titleto@return theTitledBorderobject
Defines the data model used by components like Sliders and ProgressBars. Defines four interrelated integer properties: minimum maximum extent and value. These four integers define two nested ranges like this:Class BoundedRangeModel, void setRangeProperties(int, int, int, int, boolean)minimum < value < value+extent < maximumThe outer range isminimum maximumand the inner range isvalue value+extent. The inner range must lie within the outer one i.e.valuemust be less than or equal tomaximumandvalue+extentmust greater than or equal tominimumandmaximummust be greater than or equal tominimum. There are a few features of this model that one might find a little surprising. These quirks exist for the convenience of the Swing BoundedRangeModel clients like like Slider and ScrollBar.
- The minimum and maximum set methods "correct" the other three properties to
acommodateaccommodate their new value argument. For example setting the model's minimum may change its maximum value and extent properties (in that order) to maintain the constraints specified above.- The value and extent set methods "correct" their argument to fit within the limits defined by the other three properties. For example if
value == maximumsetExtent(10)would change the extent (back) to zero.- The four BoundedRangeModel values are defined as Java Beans properties however Swing ChangeEvents are used to notify clients of changes rather than PropertyChangeEvents. This was done to keep the overhead of monitoring a BoundedRangeModel low. Changes are often reported at MouseDragged rates.
For an example of specifying custom bounded range models used by sliders see The Anatomy of a Swing-Based Program in The Java Tutorial. @version 1.
22240212/0203/0001 @author Hans Muller @see DefaultBoundedRangeModel
This method sets all of the model's data with a single method call. The method results in a single change event being generated. This is convenient when you need to adjust all the model datasimulaneouslysimultaneously and do not want individual change events to occur. @param value an int giving the current value @param extent an int giving the amount by which the value can "jump" @param min an int giving the minimum value @param max an int giving the maximum value @param isAdjusting a boolean true if a series of changes are in progress @see #setValue @see #setExtent @see #setMinimum @see #setMaximum @see #setValueIsAdjusting
A lightweight container that uses a BoxLayout object as its layout manager. Box provides several class methods that are useful for containers using BoxLayout -- even non-Box containers.The Box class can create several kinds of invisible components that affect layout: glue struts and rigid areas. If all the components your Box contains have a fixed size you might want to use a glue component (returned by
createGlue) to control the components' positions. If you need a fixed amount of space between two components try using a strut (createHorizontalStrutorcreateVerticalStrut). If you need an invisible component that always takes up the same amount of space get it by invokingcreateRigidArea.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.
A futureAsreleaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see BoxLayout @author Timothy Prinzing @version 1.36 0837 12/0503/0001
An implementation of a lightweight component that participates in layout but has no view.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
A layout manager that allows multiple components to beClass BoxLayout, constructor BoxLayout(Container, int)layedlaid out either vertically or horizontally. The components will not wrap so for example a vertical arrangement of components will stay vertically arranged when the frame is resized.
![]()
Nesting multiple panels with different combinations of horizontal and vertical gives an effect similar to GridBagLayout without the complexity. The diagram shows two panels arranged horizontally each of which contains 3 components arranged vertically.
The
Box container usesBoxLayout(unlikemanagerJPanel which defaults to flowis constructed with an axislayout).parameterYou can nest multiple boxes and add components tothat specifies the type of layout that will bethemdone.to get theThere are fourarrangementchoices:youX_AXISwant.-The BoxLayout manager that places each ofComponents are laid out horizontally from left toitsright.managedY_AXIScomponents from left to right or- Components are laid out vertically from top to bottom.WhenLINE_AXISyou- Components are laid out the way words arecreatelaid out in aBoxLayout you specify whetherline based on theitscontainer'smajorComponentOrientationaxisproperty.isIf theXcontainer'saxisComponentOrientation(whichismeanshorizontal then components are laid out horizontally otherwise they are laid out vertically. For horizontal orientations if the container's ComponentOrientation is left to rightplacement)thenor Y axiscomponents are laid(topout left tobottomrightplacement).otherwiseComponentsthey arearrangedlaidfrom leftout right torightleft.(orFor vertical orientations components are always laid out from top to bottom).inPAGE_AXIS - Components are laid out thesame order as they were addedway text lines are laid outtoon a page based on the container's ComponentOrientation property.InsteadIf theofcontainer'susingComponentOrientationBoxLayout directly many programs use the Boxis horizontal then components are laid outclass.verticallyThe Box class provides aotherwise they are laid outlightweighthorizontally. For horizontal orientations if the container'sthatComponentOrientationuses ais leftBoxLayoutto right then components are laid out left to right otherwise they are laid out right to left.Box also provides handyFor vertical orientations componentsmethodsare always laid out from top tohelpbottom.you use BoxLayoutFor all
welldirections components are arranged in the same order as they were added to the container.BoxLayout attempts to arrange components at their preferred widths (for
left to righthorizontal layout) or heights (fortop to bottomvertical layout). For aleft to righthorizontal layout if not all the components are the same height BoxLayout attempts to make all the components as high as the highest component. If that's not possible for a particular component then BoxLayout aligns that component vertically according to the component's Y alignment. By default a component hasana Y alignment of 0.5 which means that the vertical center of the component should have the same Y coordinate as the vertical centers of other components with 0.5 Y alignment.Similarly for a vertical layout BoxLayout attempts to make all components in the column as wide as the widest component
;.ifIf that fails it aligns them horizontally according to their X alignments. ForPAGE_AXISlayout horizontal alignment is done based on the leading edge of the component. In other words an X alignment value of 0.0 means the left edge of a component if the container'sComponentOrientationis left to right and it means the right edge of the component otherwise.Instead of using BoxLayout directly many programs use the Box class. The Box class is a lightweight container that uses a BoxLayout. It also provides handy methods to help you use BoxLayout well. Adding components to multiple nested boxes is a powerful way to get the arrangement you want.
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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see Box @seeComponentjava.awt.ComponentOrientation @see JComponent#getAlignmentX @seeComponentJComponent#getAlignmentY @author Timothy Prinzing @version 1.25290312/0203/01
Creates a layout manager that will lay out componentseither left to right or top to bottom as specified inalong theaxisgivenparameteraxis. @param target the container that needs to be laid out @param axis the axis to lay out components along.ForCanleft-to-rightbelayoutonespecifyof:BoxLayout.X_AXIS; fortop-to-bottomBoxLayout.Y_AXISlayoutBoxLayout.LINE_AXISspecifyorBoxLayout.@exception AWTError if the value ofYPAGE_AXISaxisis invalid
This class is used to create a multiple-exclusion scope for a set of buttons. Creating a set of buttons with the sameClass ButtonGroup, constructor ButtonGroup()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.
A futureAsreleaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.27 0232 12/0203/0001 @author Jeff Dinkins
Creates a new ButtonGroup.
Class ButtonGroup, void add(AbstractButton)Adds the button to the group. @param b the button to be addedClass ButtonGroup, int getButtonCount()
Returns the number of buttons in the group. @return the button countClass ButtonGroup, Enumeration getElements()
Class ButtonGroup, ButtonModel getSelection()ReturnReturns all the buttons that are participating in this group. @return anEnumerationof the buttons in this group
Class ButtonGroup, boolean isSelected(ButtonModel)ReturnReturns the model of the selected button. @return the selected button model.
ReturnsClass ButtonGroup, void remove(AbstractButton)thewhether aButtonModelis selected. @returnvaluetrueforif the button.is selected otherwise returnsfalse
Removes the button from the group. @param b the button to be removedClass ButtonGroup, void setSelected(ButtonModel, boolean)
Sets the selected value for theButtonModel. Only one button in the group may be selected at a time. @param theButtonModel@paramtrueif this button is to be selected otherwisefalse
State Model for buttons. This model is used for check boxes and radio buttons which are special kinds of buttons as well as for normal buttons. For check boxes and radio buttons pressing the mouse selects the button. For normal buttons pressing the mouse "arms" the button. Releasing the mouse over the button then initiates a button press firing its action event. Releasing the mouse elsewhere disarms the button.In use a UI will invoke #setSelected when a mouse click occurs over a check box or radio button. It will invoke #setArmed when the mouse is pressed over a regular button and invoke #setPressed when the mouse is released. If the mouse travels outside the button in the meantime
setArmed(false)will tell the button not to fire when it seessetPressed. (If the mouse travels back in the button will be rearmed.)Note:@version 1.
A button is triggered when it is both "armed" and "pressed".23 0224 12/0203/0001 @author Jeff Dinkins
This interface defines the methods any general editor should be able to implement.Class CellEditor, void addCellEditorListener(CellEditorListener)Having this interface enables complex components (the client of the editor) such as
JListJTreeandJTableto allow any generic editor to edit values in a table cell or tree cell etc. Without this generic editor interfaceJTablewould have to know about specific editors such asJTextFieldJCheckBoxJComboBoxetc. In addition without this interface clients of editors such asJTablewould not be able to work with any editors developed in the future by the user or a 3rd party ISV.To use this interface a developer creating a new editor can have the new component implement the interface. Or the developer can choose a wrapper based
approchapproach and provide a companion object which implements theCellEditorinterface (SeeJCellEditorfor example). The wrapperapprochapproach is particularly useful if the user want to use a 3rd party ISV editor withJTablebut the ISV didn't implement theCellEditorinterface. The user can simply create an object that contains an instance of the 3rd party editor object and "translate" theCellEditorAPI into the 3rd party editor's API. @see javax.swing.event.CellEditorListener @version 1.19 0222 12/0203/0001 @author Alan Chung
Class CellEditor, void cancelCellEditing()AddAdds a listener to the list that's notified when the editorstartsstops or cancels editing. @param l the CellEditorListener
Class CellEditor, Object getCellEditorValue()TellTells the editor to cancel editing and not accept any partially edited value.
Returns the value contained in the editor. @return the value contained in the editorClass CellEditor, boolean isCellEditable(EventObject)
Class CellEditor, void removeCellEditorListener(CellEditorListener)AskAsks the editor if it can start editing usinganEvent.anEventis in the invoking component coordinate system. The editor can not assume the Component returned bygetCellEditorComponentis installed. This method is intended for the use of client to avoid the cost of setting up and installing the editor component if editing is not possible. If editing can be started this method returns true. @param anEvent the event the editor should use to consider whether to begin editing or not().@return true if editing can be started.@see #shouldSelectCell
Class CellEditor, boolean shouldSelectCell(EventObject)RemoveRemoves a listener from the list that's notified @param l the CellEditorListener
Class CellEditor, boolean stopCellEditing()TheReturnsreturn value of shouldSelectCell() is a boolean indicatingtruewhetherif the editing cell should be selectedorfalsenototherwise. Typically the return value is true because is most cases the editing cell should be selected. However it is useful to return false to keep the selection from changing for some types of edits. eg. A table that contains a column of check boxes the user might want to be able to change those checkboxes without altering the selection. (See Netscape Communicator for just such an example) Of course it is up to the client of the editor to use the return value but it doesn't need to if it doesn't want to. @param anEvent the event the editor should use to start editing.@return true if the editor would like the editing cell to be selected; otherwise returns false @see #isCellEditable
TellTells the editor to stop editing and accept any partially edited value as the value of the editor. The editor returns false if editing was not stopped; this is useful for editorswhich validatesthat validate and can not accept invalid entries. @return true if editing was stopped; false otherwise
This class is inserted in between cell renderers and the components that use them. It just exists to thwart the repaint() and invalidate() methods which would otherwiseClass CellRendererPane, void invalidate()propogatepropagate up the tree when the renderer was configured. It's used by the implementations of JTable JTree and JList. For example here's how CellRendererPane is used in the code the paints each row in a JList:cellRendererPane = new CellRendererPane(); ... Component rendererComponent = renderer.getListCellRendererComponent(); renderer.configureListCellRenderer(dataModel.getElementAt(row) row); cellRendererPane.paintComponent(g rendererComponent this x y w h);A renderer component must override isShowing() and unconditionally return true to work correctly because the Swing paint does nothing for components with isShowing false.
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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.34 0836 12/0503/0001 @author Hans Muller
Overridden to avoidClass CellRendererPane, void paintComponent(Graphics, Component, Container, int, int, int, int, boolean)propogatingpropagating a invalidate up the tree when the cell renderer child is configured.
Paint a cell renderer component c on graphics object g. Before the component is drawn it's reparented to this (if that'sneccessarynecessary) it's bounds are set to w h and the graphics object is (effectively) translated to x y. If it's a JComponent double buffering is temporarily turned off. After the component is painted it's bounds are reset to -w -h 0 0 so that if it's the last renderer component painted it will not start consuming input. The Container p is the component we're actually drawing on typically it's equal to this.getParent(). If shouldValidate is true the component c will be validated before painted.
The editor component used for JComboBox components. @version 1.10 0211 12/0203/0001 @author Arnaud Weber
Class ComboBoxModel, Object getSelectedItem()ComboBoxDataModelAisdata model for a combo box. This interface extendsListDataModel and adds the conceptwithof a selected item.ThisThe selected item is generally the item which is visible in themodel since itcombo box displayisarea.The selected item
may notalwaysnecessarilyinbe managed by the underlyingListModel. This disjoint behavior allows for the temporary storage and retrieval of a selected itemlistin the model. @version 1.13 12/03/01 @author Arnaud Weber
Class ComboBoxModel, void setSelectedItem(Object)ReturnReturns the selected item @return The selected item ornullif there is no selection
Set the selected item. The implementation of this method should notify all registeredListDataListeners that the contents have changed. @param anItem the list object to select ornullto clear the selection
AComponentInputMapis anInputMapassociated with a particularJComponent. The component is automatically notified whenever theComponentInputMapchanges.ComponentInputMaps are used forWHEN_IN_FOCUSED_WINDOWbindings. @version 1.6 027 12/0203/0001 @author Scott Violet
Graphics subclass supporting graphics debugging. Overrides most methods from Graphics. DebugGraphics objects are rarely created by hand. They are most frequently created automatically when a JComponent's debugGraphicsOptions are changed using the setDebugGraphicsOptions() method.Class DebugGraphics, int BUFFERED_OPTIONNOTE: You must turn off double buffering to use DebugGraphics: RepaintManager repaintManager = RepaintManager.currentManager(component); repaintManager.setDoubleBufferingEnabled(false); @see JComponent#setDebugGraphicsOptions @see RepaintManager#currentManager @see RepaintManager#setDoubleBufferingEnabled @version 1.
20 0722 12/2603/0001 @author Dave Karlton
Show buffered operations in aseperateseparateFrame.
A generic implementation of BoundedRangeModel.Class DefaultBoundedRangeModel, constructor DefaultBoundedRangeModel(int, int, int, 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.35 0242 12/0203/0001 @author David Kloba @author Hans Muller @see BoundedRangeModel
Initializes value extent minimum and maximum. Adjusting is false. Throws anClass DefaultBoundedRangeModel, void addChangeListener(ChangeListener)IllegalArgumentExceptionif the following constraints aren't satisfied:min < value < value+extent < max
Adds a ChangeListener. The change listeners are run each time any one of the Bounded Range model properties changes. @param l the ChangeListener to add @see #removeChangeListener @see BoundedRangeModel#addChangeListener
Class DefaultBoundedRangeModel, void fireStateChanged()Class DefaultBoundedRangeModel, int getExtent()RunRuns eachChangeListenersChangeListener'sstateChangedmethod. @see #setRangeProperties @see EventListenerList()
Class DefaultBoundedRangeModel, EventListener[] getListeners(Class)ReturnReturns the model's extent. @return the model's extent @see #setExtent @see BoundedRangeModel#getExtent
Class DefaultBoundedRangeModel, int getMaximum()ReturnReturns an array of all the objects currently registered asFooListeners upon this model.FooListeners are registered using theaddFooListenermethod.You can specify the
listenerslistenerTypeargument with a class literal such asFooListener.class. For example you can query aDefaultBoundedRangeModelinstancemfor its changeofwith thegivenfollowingtypecode:thatChangeListener[] cls = (ChangeListener[])(m.getListeners(ChangeListener.class));wereIfaddedno such listenerstoexist thismodelmethod returns an empty array. @returnsparamalllistenerType the type ofthelisteners requested; this parameter should specify an interface that descends fromjava.util.EventListener@return an array of all objectsrecievingregistered aslistenerTypeFooListenersnotificationsonfromthis model or an empty array if no such listeners have been added @exception ClassCastException iflistenerTypedoesn't specify a class or interface that implementsjava.util.EventListener@see #getChangeListeners @since 1.3
Class DefaultBoundedRangeModel, int getMinimum()ReturnReturns the model's maximum. @return the model's maximum @see #setMaximum @see BoundedRangeModel#getMaximum
Class DefaultBoundedRangeModel, int getValue()ReturnReturns the model's minimum. @return the model's minimum @see #setMinimum @see BoundedRangeModel#getMinimum
Class DefaultBoundedRangeModel, boolean getValueIsAdjusting()ReturnReturns the model's current value. @return the model's current value @see #setValue @see BoundedRangeModel#getValue
Returns true if the value is in the process of changing as a result of actions being taken by the user. @return the value of the valueIsAdjusting property @see #setValue @see BoundedRangeModel#getValueIsAdjusting
Class DefaultBoundedRangeModel, void removeChangeListener(ChangeListener)Removes aClass DefaultBoundedRangeModel, void setRangeProperties(int, int, int, int, boolean)ChangeListener. @param l theChangeListenerto remove @see #addChangeListener @see BoundedRangeModel#removeChangeListener
Sets all of theClass DefaultBoundedRangeModel, void setValueIsAdjusting(boolean)BoundedRangeModelproperties after forcing the arguments to obey the usual constraints:minimum < value < value+extent < maximumAt most one
ChangeEventis generated. @see BoundedRangeModel#setRangeProperties @see #setValue @see #setExtent @see #setMinimum @see #setMaximum @see #setValueIsAdjusting
Sets the valueIsAdjusting property. @see #getValueIsAdjusting @see #setValue @see BoundedRangeModel#setValueIsAdjusting
Class DefaultBoundedRangeModel, String toString()Returns a string that displays all of the BoundedRangeModel properties.
Class DefaultBoundedRangeModel, ChangeEvent changeEventOnly one ChangeEvent is needed per model instance since the event's only (read-only) state is the source property. The source of events generated here is always "this".
The default implementation of aClass DefaultButtonModel, constructor DefaultButtonModel()Buttoncomponent's data model.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.32 0241 12/0203/0001 @author Jeff Dinkins
Constructs a default JButtonModel.
Class DefaultButtonModel, void addActionListener(ActionListener)Adds an ActionListener to the button. @param l the listener to add
Class DefaultButtonModel, void addChangeListener(ChangeListener)Adds a ChangeListener to the button. @param l the listener to add
Class DefaultButtonModel, void addItemListener(ItemListener)Adds an ItemListener to the button. @param l the listener to add
Class DefaultButtonModel, String getActionCommand()Returns the action command for this button. @return the String that identifies the generated event @see #setActionCommand
Class DefaultButtonModel, ButtonGroup getGroup()Returns the group that this button belongs to. Normally used with radio buttons which are mutually exclusive within their group. @return a ButtonGroup that this button belongs to @since 1.3
Class DefaultButtonModel, EventListener[] getListeners(Class)Class DefaultButtonModel, Object[] getSelectedObjects()ReturnReturns an array of all the objects currently registered asFooListeners upon this model.FooListeners are registered using theaddFooListenermethod.You can specify the
listenerslistenerTypeargument with a class literal such asFooListener.class. For example you can query aDefaultButtonModelinstancemfor its actionofwith thegivenfollowingtypecode:thatActionListener[] als = (ActionListener[])(m.getListeners(ActionListener.class));were added toIf no such listeners exist thismodelmethod returns an empty array. @returns allparam listenerType the type ofthelisteners requested; this parameter should specify an interface that descends fromjava.util.EventListener@return an array of all objectsrecievingregistered aslistenerTypeFooListenersnotificationsonfromthis model or an empty array if no such listeners have been added @exception ClassCastException iflistenerTypedoesn't specify a class or interface that implementsjava.util.EventListener@see #getActionListeners @see #getChangeListeners @see #getItemListeners @since 1.3
Class DefaultButtonModel, boolean isEnabled()OverridenOverridden to returnnull.
IndicatesClass DefaultButtonModel, boolean isPressed()ifwhether the button can be selected or pressed by an input device (such as a mouse pointer). (Checkbox-buttons are selected regular buttons are "pressed".) @return true if the button is enabled and therefore selectable (or pressable)
IndicatesClass DefaultButtonModel, void removeActionListener(ActionListener)ifwhether button has been pressed. @return true if the button has been pressed
Removes an ActionListener from the button. @param l the listener to remove
Class DefaultButtonModel, void removeChangeListener(ChangeListener)Removes a ChangeListener from the button. @param l the listener to remove
Class DefaultButtonModel, void removeItemListener(ItemListener)Removes an ItemListener from the button. @param l the listener to remove
Class DefaultButtonModel, void setActionCommand(String)Sets theClass DefaultButtonModel, void setGroup(ButtonGroup)actionCommandstring that gets sent as part of the event when the button is pressed. @param s theStringthat identifies the generated event
Identifies the group this button belongs to -- needed for radio buttons which are mutually exclusive within their group. @param group the ButtonGroup this button belongs to
Class DefaultButtonModel, void setSelected(boolean)Selects or deselects the button. @param b true selects the button false deselects the buttonClass DefaultButtonModel, ChangeEvent changeEvent.
Only one ChangeEvent is needed per button model instance since the event's only state is the source property. The source of events generated is always "this".
The default editor for table and tree cells.Class DefaultCellEditor, constructor DefaultCellEditor(JCheckBox)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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.38 0246 12/0203/0001 @author Alan Chung @author Philip Milne
Constructs aClass DefaultCellEditor, constructor DefaultCellEditor(JComboBox)DefaultCellEditorobject that uses a check box. @param x aJCheckBoxobject...
Constructs aClass DefaultCellEditor, constructor DefaultCellEditor(JTextField)DefaultCellEditorobject that uses a combo box. @param x aJComboBoxobject...
Constructs aClass DefaultCellEditor, int getClickCountToStart()DefaultCellEditorthat uses a text field. @param x aJTextFieldobject...
Class DefaultCellEditor, Component getComponent()ClickCountToStartReturnscontrolsthe number of clicksrequiredneeded to start editing. @returns the number of clicks needed to start editing
Returnsthea reference to the editor component. @return the editorComponent
The default model for combo boxes. @version 1.11 0215 12/0203/0001 @author Arnaud Weber @author Tom Santos
This is anClass DefaultDesktopManager, void activateFrame(JInternalFrame)implementaionimplementation of theDesktopManager. It currently implementsathe basic behaviors for managingJInternalFramesJInternalFrames in an arbitrary parent.JInternalFramesJInternalFrames that are not children of aJDesktopwill use this component to handle their desktop-like actions. @see JDesktopPane @see JInternalFrame @version 1.41 0245 12/0203/0001 @author David Kloba @author Steve Wilson
This will activate f moving it to the front. It will set the current active frame's (if any)Class DefaultDesktopManager, void closeFrame(JInternalFrame)IS_SELECTED_PROPERTYtofalse. There can be only one active frame across all Layers. @param f theJInternalFrameto be activated
Removes the frame and if necessary theClass DefaultDesktopManager, void deiconifyFrame(JInternalFrame)desktopIconfrom its parent. @param f theJInternalFrameto be removed
Removes the desktopIcon from its parent and adds its frame to the parent. @param f the JInternalFrame to be de-iconified
Class DefaultDesktopManager, void dragFrame(JComponent, int, int)Moves the visible location of the frame being dragged to the location specified. The means by which this occurs can vary depending on the dragging algorithm being used. The actual logical location of the frame might not change until endDraggingFrame is called.
Class DefaultDesktopManager, void iconifyFrame(JInternalFrame)Removes the frame from its parent and adds itsClass DefaultDesktopManager, void maximizeFrame(JInternalFrame)desktopIconto the parent. @param f theJInternalFrameto be iconified
Resizes the frame to fill its parents bounds. @param the frame to be resizedClass DefaultDesktopManager, void minimizeFrame(JInternalFrame)
Restores the frame back to its size and position prior to aClass DefaultDesktopManager, void removeIconFor(JInternalFrame)maximizeFramecall. @param f the()JInternalFrameto be restored
Class DefaultDesktopManager, void resizeFrame(JComponent, int, int, int, int)ConvienceConvenience method to remove the desktopIcon of f is necessary.
Calls setBoundsForFrame() with the new values. @param f the component to be resized @param newX the new x-coordinate @param newY the new y-coordinate @param newWidth the new width @param newHeight the new height
Class DefaultDesktopManager, void setBoundsForFrame(JComponent, int, int, int, int)This moves the JComponent and repaints the damaged areas.
Class DefaultDesktopManager, void setPreviousBounds(JInternalFrame, Rectangle)Stores the bounds of the component just before a maximize call. @param f the component about to be resized @param r the normal bounds to be saved awayClass DefaultDesktopManager, void setWasIcon(JInternalFrame, Boolean)
Sets that the component has been iconized and the bounds of the desktopIcon are valid.
Default swingThis class has been obsoleted by the 1.4 focusmanagerAPIs. While client code may still use this class developers are strongly encouraged to usejava.awt.KeyboardFocusManagerandjava.awt.DefaultKeyboardFocusManagerinstead. Please see the FocusimplementationSpecification for more information. @see Focus Specification @version 1.15 0726 12/1303/9901 @author Arnaud Weber @author David Mendenhall
Renders an item in a list.Implementation Note: This class overrides
validaterevalidaterepaintandfirePropertyChangesolely to improve performance. If not overridden these frequently called methods would execute code paths that are unnecessary for the default list cell renderer. If you write your own renderer take care to weigh the benefits and drawbacks of overriding these methods.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.18 0721 12/2603/0001 @author Philip Milne @author Hans Muller
A subclass of DefaultListCellRenderer that implements UIResource. DefaultListCellRenderer doesn't implement UIResource directly so that applications can safely override the cellRenderer property with DefaultListCellRenderer subclasses.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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
This class loosely implements theClass DefaultListModel, void add(int, Object)java.util.VectorAPI in that it implements the 1.1.x version ofjava.util.Vectorhas no collection class support and notifies theListDataListenersListDataListeners when changes occur. Presently it delegates to aVectorin a future release it will be a real Collection implementation.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.26 0231 12/0203/0001 @author Hans Muller
Inserts the specified element at the specified position in this list.Class DefaultListModel, void addElement(Object)Throws an
ArrayIndexOutOfBoundsExceptionif the index is out of range (index < 0 || index >). @param index index at which the specified element is to be inserted=size().@param element element to be inserted.
Adds the specified component to the end of this list. @param obj the component to be addedClass DefaultListModel, boolean contains(Object).@see Vector#addElement(Object)
TestsClass DefaultListModel, void copyInto(Object[])ifwhether the specified object is a component in this list. @param elem an object.@returntrueif the specified object is the same as a component in this list @see Vector#contains(Object)
Copies the components of this list into the specified array. The array must be big enough to hold all the objects in this list else anClass DefaultListModel, Object elementAt(int)IndexOutOfBoundsExceptionis thrown. @param anArray the array into which the components get copied.@see Vector#copyInto(Object[])
Returns the component at the specified index. Throws anClass DefaultListModel, Enumeration elements()ArrayIndexOutOfBoundsExceptionif the index is negative or not less than the size of the list.Note: Although this method is not deprecated the preferred method to use is@param index an index into this listget(int)which implements theListinterface defined in the 1.2 Collections framework..@return the component at the specified index.@see #get(int) @see Vector#elementAt(int)
Returns an enumeration of the components of this list. @return an enumeration of the components of this listClass DefaultListModel, void ensureCapacity(int).@see Vector#elements()
Increases the capacity of this list if necessary to ensure that it can hold at least the number of components specified by the minimum capacity argument. @param minCapacity the desired minimum capacityClass DefaultListModel, Object firstElement().@see Vector#ensureCapacity(int)
Returns the first component of this list. Throws aClass DefaultListModel, Object get(int)NoSuchElementExceptionif this vector has no components*. @return the first component of this list @see Vector#firstElement()
Returns the element at the specified position in this list.Class DefaultListModel, Object getElementAt(int)Throws an
ArrayIndexOutOfBoundsExceptionif the index is out of range (index < 0 || index >= size()). @param index index of element to return.
Returns the component at the specified index.Class DefaultListModel, int getSize()Note: Although this method is not deprecated the preferred method to use is@param index an index into this listget(int)which implements theListinterface defined in the 1.2 Collections framework..@return the component at the specified index.@exception ArrayIndexOutOfBoundsException if theindexis negative ornot lessgreater than the current size of this list. given.@see #get(int)
Returns the number of components in this list.Class DefaultListModel, int indexOf(Object)This method is identical to
sizewhich implements the()Listinterface defined in the 1.2 Collections framework. This method exists in conjunction withsetSizeso that()"sizeis identifiable as a JavaBean property. @return the number of components in this list".@see #size()
Searches for the firstClass DefaultListModel, int indexOf(Object, int)occurenceoccurrence ofthe given argumentelem. @param elem an object.@return the index of the first occurrence of the argument in this list; returns-1if the object is not found.@see Vector#indexOf(Object)
Searches for the firstClass DefaultListModel, void insertElementAt(Object, int)occurenceoccurrence ofthe given argumentelembeginning the search atindex. @param elem anobject.desired component @param index the index from which tostartbegin searchingfrom.@return the indexofwhere the first occurrence ofthe object argument in thiselemlist at positionis found afterindexor later in the list; returns-1if theobjectelemis not found.in the list @see Vector#indexOf(Object int)
Inserts the specified object as a component in this list at the specifiedClass DefaultListModel, boolean isEmpty()index.Throws an
ArrayIndexOutOfBoundsExceptionif the index is invalid.Note: Although this method is not deprecated the preferred method to use is@param obj the component to insertadd(int Object)which implements theListinterface defined in the 1.2 Collections framework..@param index where to insert the new component.@exception ArrayIndexOutOfBoundsException if the index was invalid.@see #add(int Object) @see Vector#insertElementAt(Object int)
TestsClass DefaultListModel, Object lastElement()ifwhether this list hasnoany components. @returntrueif and only if this list has no components that is its size is zero;falseotherwise.@see Vector#isEmpty()
Returns the last component of the list. Throws aClass DefaultListModel, int lastIndexOf(Object)NoSuchElementExceptionif this vector has no components*. @return the last component of the list @see Vector#lastElement()
Returns the index of the last occurrence ofClass DefaultListModel, int lastIndexOf(Object, int)the specified object in this listelem. @param elem the desired component.@return the index of the last occurrence ofthe specified objecteleminthisthe list; returns-1if the object is not found.@see Vector#lastIndexOf(Object)
Searches backwards forClass DefaultListModel, Object remove(int)the specified objectelemstarting from the specified index and returns an index to it. @param elem the desired component.@param index the index to start searching from.@return the index of the last occurrence of thespecified objectelemin this list at position less thanindexin the list; returns-1if the object is not found.@see Vector#lastIndexOf(Object int)
Removes the element at the specified position in this list. Returns the element that was removed from the list.Class DefaultListModel, void removeAllElements()Throws an
ArrayIndexOutOfBoundsExceptionif the index is out of range (index < 0 || index >= size()). @param index the index of the element to removed.
Removes all components from this list and sets its size to zero.Class DefaultListModel, boolean removeElement(Object)Note: Although this method is not deprecated the preferred method to use is@see #clear() @see Vector#removeAllElements()clearwhich implements the()Listinterface defined in the 1.2 Collections framework.
Removes the first (lowest-indexed) occurrence of the argument from this list. @param obj the component to be removedClass DefaultListModel, void removeElementAt(int).@returntrueif the argument was a component of this list;falseotherwise.@see Vector#removeElement(Object)
Deletes the component at the specified index.Class DefaultListModel, void removeRange(int, int)Throws an
ArrayIndexOutOfBoundsExceptionif the index is invalid.Note: Although this method is not deprecated the preferred method to use is@param index the index of the object to removeremove(int)which implements theListinterface defined in the 1.2 Collections framework..@see #remove(int) @see Vector#removeElementAt(int)
Deletes the components at the specified range of indexes. The removal is inclusive so specifying a range of (1 5) removes the component at index 1 and the component at index 5 as well as all components in between.Class DefaultListModel, Object set(int, Object)Throws an
ArrayIndexOutOfBoundsExceptionif the index was invalid. Throws anIllegalArgumentExceptioniffromIndex > toIndex. @param fromIndex the index of the lower end of the range @param toIndex the index of the upper end of the range @see #remove(int)
Replaces the element at the specified position in this list with the specified element.Class DefaultListModel, void setElementAt(Object, int)Throws an
ArrayIndexOutOfBoundsExceptionif the index is out of range (index < 0 || index >= size()). @param index index of element to replace.@param element element to be stored at the specified position.@return the element previously at the specified position.
Sets the component at the specifiedClass DefaultListModel, void setSize(int)indexof this list to be the specified object. The previous component at that position is discarded.Throws an
ArrayIndexOutOfBoundsExceptionif the index is invalid.Note: Although this method is not deprecated the preferred method to use is@param obj what the component is to be set toset(int Object)which implements theListinterface defined in the 1.2 Collections framework..@param index the specified index.@see #set(int Object) @see Vector#setElementAt(Object int)
Sets the size of this list. @param newSize the new size of this listClass DefaultListModel, int size().@see Vector#setSize(int)
Returns the number of components in this list. @return the number of components in this listClass DefaultListModel, Object[] toArray().@see Vector#size()
Returns an array containing all of the elements in this list in the correct order.Throws an ArrayStoreException if the runtime type of the array a is not a supertype of the runtime type of every element in this list. @param a the array into which the elements of the list are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose.@return an array containing the elements of the list.@see Vector#toArray()
Default data model for list selections.Class DefaultListSelectionModel, EventListener[] getListeners(Class)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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.55 0265 12/0203/0001 @author Philip Milne @author Hans Muller @see ListSelectionModel
Returns an array of all the objects currently registered asFooListeners upon this model.FooListeners are registered using theaddFooListenermethod.You can specify the
listenerslistenerTypeargument with a class literal such asFooListener.class. For example you can query aDefaultListSelectionModelinstancemfor its list selectionofwith thegivenfollowingtypecode:thatListSelectionListener[] lsls = (ListSelectionListener[])(m.getListeners(ListSelectionListener.class));wereIfaddedno suchtolisteners exist thismodelmethod returns an empty array. @param listenerType the type of listeners requested; this parameter should specify an interface that descends fromjava.util.EventListener@returnallan array oftheall objectsreceivingregistered asslistenerTypeFoonotificationsListenerfromon this model or an empty array if no such listeners have been added @exception ClassCastException iflistenerTypedoesn't specify a class or interface that implementsjava.util.EventListener@see #getListSelectionListeners @since 1.3
A generic implementation of SingleSelectionModel.Class DefaultSingleSelectionModel, void addChangeListener(ChangeListener)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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.25 0232 12/0203/0001 @author Dave Moore
Adds a ChangeListener to the button.
Class DefaultSingleSelectionModel, EventListener[] getListeners(Class)Class DefaultSingleSelectionModel, void removeChangeListener(ChangeListener)ReturnReturns an array of all the objects currently registered asFooListeners upon this model.FooListeners are registered using theaddFooListenermethod.You can specify the
listenerslistenerTypeargument with a class literal such asFooListener.class. For example you can query aDefaultSingleSelectionModelinstancemfor its changeofwith thegivenfollowingtypecode:thatChangeListener[] cls = (ChangeListener[])(m.getListeners(ChangeListener.class));wereIfaddedno such listenerstoexist thismodelmethod returns an empty array. @returnsparamalllistenerType the type ofthelisteners requested; this parameter should specify an interface that descends fromjava.util.EventListener@return an array of all objectsrecievingregistered aslistenerTypeFooListenersnotificationsonfromthis model or an empty array if no such listeners have been added @exception ClassCastException iflistenerTypedoesn't specify a class or interface that implementsjava.util.EventListener@see #getChangeListeners @since 1.3
Removes a ChangeListener from the button.
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:Class DesktopManager, void dragFrame(JComponent, int, int)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.) @see JDesktopPane @see JInternalFrame @see JInternalFrame.JDesktopIcon @version 1.10 0212 12/0203/0001 @author David Kloba
The user has moved the frame. Calls to this method will beClass DesktopManager, void resizeFrame(JComponent, int, int, int, int)preceededpreceded by calls to beginDraggingFrame(). Normally f will be a JInternalFrame.
The user has resized the component. Calls to this method will beClass DesktopManager, void setBoundsForFrame(JComponent, int, int, int, int)preceededpreceded by calls to beginResizingFrame(). Normally f will be a JInternalFrame.
This is aprimativeprimitive reshape method.
Class FocusManager, void disableSwingFocusManager()SwingThis class has been obsoleted by the 1.4 focus APIs. While client code may still use this class developers are strongly encouraged to usejava.awt.KeyboardFocusManagerandjava.awt.DefaultKeyboardFocusManagerinstead. Please see the Focus Specification for more information. @see FocusManagerSpecification @version 1.11 0223 12/0203/0001 @author Arnaud Weber @author David Mendenhall
Class FocusManager, FocusManager getCurrentManager()DisableChangesSwing's focus manager forthecallingcurrentthreadKeyboardFocusManager'sthread group. Call thisdefaultmethodFocusTraversalPolicyiftoyour applicationDefaultFocusTraversalPolicy.mixes@see java.awtcomponents and swing's components.DefaultFocusTraversalPolicyYour@seeapplicationjava.awt.KeyboardFocusManager#setDefaultFocusTraversalPolicywill@deprecatedthen useas ofthe1.4awt focusreplaced bymanagerKeyboardFocusManager.setDefaultFocusTraversalPolicy(FocusTraversalPolicy)
Class FocusManager, boolean isFocusManagerEnabled()ReturnReturns theFocusManagercurrentKeyboardFocusManagerinstance for the calling thread'sTherecontext.is@returnonethisFocusManagerthread'spercontext'sKeyboardFocusManagerthread@seegroup#setCurrentManager
Class FocusManager, void processKeyEvent(Component, KeyEvent)ReturnReturns whetherSwing'sthefocus manager isapplication has invokedenableddisableSwingFocusManager(). @see #disableSwingFocusManager @deprecated As of 1.4 replaced byKeyboardFocusManager.getDefaultFocusTraversalPolicy()
This methodClass FocusManager, void setCurrentManager(FocusManager)is called by JComponentsinitiateswhenakey eventfocusoccurs.traversalJComponent gives key events tooperation if and only if thefocusKeyEventmanager first then torepresents a focus traversal keylistenersforthen tothekeyboard UIspecifieddispatcherfocusedComponent.This method should lookItat theiskey event and changeexpected that focusedComponent is thefocused component if thecurrentkey event matches thefocus owner although thisreceiver'sneedfocus manager hot keysnot be the case.ForIfexample the defaultit is not focusmanagertraversal willchange the focusnevertheless proceed as ifthe key event matches TABfocusedComponentor Shift + TABwere the focus owner.The@paramfocus managerfocusedComponentshould callthe Componentconsume()thatonisanEventtheifbasisanEventforhas beena focusprocessed.traversalfocusedComponentoperationisif thecomponent thatspecifiedcurrently has theevent represents a focus. Note: FocusManager will receivebothtraversalKEY_PRESSEDkeyandforKEY_RELEASEDthekeyComponentevents.@paramIf onee the eventis consumed thethatother one should be consumedmay represent a focus traversaltoo.key
Class FocusManager, String FOCUS_MANAGER_CLASS_PROPERTYSetSets theFocusManagercurrentthatKeyboardFocusManagershould be usedinstance for theforcalling thread's context. Ifnullis specified then the currentKeyboardFocusManageris replaced with a new instance ofDefaultKeyboardFocusManager.If a
the calling thread must be granted theSecurityManageris installedAWTPermission"replaceKeyboardFocusManager" in order to replace the the currentKeyboardFocusManager.aFocusManagerIf this permission is not granted this method willbethrow aSecurityExceptionand thedefaultcurrentfocusKeyboardFocusManagermanagerwillforbe unchanged. @param newManager thecallingnewKeyboardFocusManagerfor this thread'sthreadcontext @see #getCurrentManagergroup@see java.awt.DefaultKeyboardFocusManager @throws SecurityException if the calling thread does not have permission to replace the currentKeyboardFocusManager
Thispropertyfield is obsolete and itsnameuse isuseddiscouragedto getsince its specification is incompatible with theFocusManager1.4implementationfocusthatAPIs.should be used forThe current FocusManager is no longer agivenproperty of the UI. Client code must query for the current FocusManager usingKeyboardFocusManager.getCurrentKeyboardFocusManager(). See the Focus Specification for more information. @see java.awt.KeyboardFocusManager#getCurrentKeyboardFocusManager @see Focus Specification
An image filter that "disables" an image by turning it into a grayscale image and brightening the pixels in the image. Used by buttons to create an image for a disabled button. @author Jeff Dinkins @author Tom Ball @author Jim Graham @version 1.12 0213 12/0203/0001
An implementation of the Icon interface that paints Icons from Images. Images that are created from a URL or filename are preloaded using MediaTracker to monitor the loaded state of the image.For further information and examples of using image icons see How to Use Icons 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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.46 0449 12/0603/0001 @author Jeff Dinkins @author Lynn Monsanto
This class implements accessibility support for theImageIconclass. It provides an implementation of the Java Accessibility API appropriate to image icon user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
InputMapprovides a binding between an input event (currently onlyKeyStrokes are used) and anObject.InputMaps are usually used with anActionMapto determine anActionto perform when a key is pressed. AnInputMapcan have a parent that is searched for bindings not defined in theInputMap.As with
ActionMapif you create a cycle eg:InputMap am = new InputMap(); InputMap bm = new InputMap(): am.setParent(bm); bm.setParent(am);some of the methods will cause a StackOverflowError to be thrown. @version 1.9 0211 12/0203/0001 @author Scott Violet @since 1.3
The purpose of this class is to help clients support smooth focus navigation through GUIs with text fields. Such GUIs often need to ensure that the text entered by the user is valid (for example that it's in the proper format) before allowing the user to navigate out of the text field. To do this clients create a subclass ofInputVerifierand usingJComponent'ssetInputVerifiermethod attach an instance of their subclass to theJComponentwhose input they want to validate. Before focus is transfered to another Swing component that requests it the input verifier'sshouldYieldFocusmethod is called. Focus is transfered only if that method returnstrue.The following example has two text fields with the first one expecting the string "pass" to be entered by the user. If that string is entered in the first text field then the user can advance to the second text field either by clicking in it or by pressing TAB. However if another string is entered in the first text field then the user will be unable to transfer focus to the second text field.
import java.awt.*; import java.util.*; import java.awt.event.*; import javax.swing.*; // This program demonstrates the use of the Swing InputVerifier class. // It creates two text fields; the first of the text fields expects the // string "pass" as input and will allow focus to advance out of it // only after that string is typed in by the user. public class VerifierTest extends JFrame { public VerifierTest@since 1.3() { JTextFieldtf; tftf1 = new JTextField ("TextField1Type \"pass\" here"); getContentPane().add (tftf1 BorderLayout.NORTH);tftf1.setInputVerifier(new PassVerifier());tfJTextField tf2 = new JTextField ("TextField2"); getContentPane().add (tftf2 BorderLayout.SOUTH);addWindowListener (new MyWAdapter ()); } public static void main (String [] args) { FrameWindowListenerfl = newVerifierTest (); f.pack(); f.showWindowAdapter(); } class MyWAdapter extends WindowAdapter{ public void windowClosing(WindowEventevente) { System.exit(0); } }; addWindowListener(l); } class PassVerifier extends InputVerifier { public boolean verify(JComponent input) { JTextField tf = (JTextField) input;Stringreturn "pass=".equals(tf.getText());if}(pass.equals} public static void main("pass")String[] args)return{true;Frameelse returnf =falsenew VerifierTest();}f.pack(); f.setVisible(true); } }
An extended version of java.applet.Applet that adds support for the JFC/Swing component architecture. You can find task-oriented documentation about usingClass JApplet, constructor JApplet()JAppletin The Java Tutorial in the section How to Make Applets.The JApplet class is slightly incompatible with java.applet.Applet. JApplet contains a JRootPane as it's only child. The contentPane should be the parent of any children of the JApplet. This is different than java.applet.Applet e.g. to add a child to an an java.applet.Applet you'd write:
applet.add(child);However using JApplet you need to add the child to the JApplet's contentPane instead:applet.getContentPane().add(child);The same is true for setting LayoutManagers removing components listing children etc. All these methods should normally be sent to the contentPane() instead of the JApplet itself. The contentPane() will always be non-null. Attempting to set it to null will cause the JApplet to throw an exception. The default contentPane() will have a BorderLayout manager set on it.Please see the JRootPane documentation for a complete description of the contentPane glassPane and layeredPane properties.
For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JAppletkey 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer true attribute: containerDelegate getContentPane description: Swing's Applet subclass. @version 1.44 0853 12/0503/0001 @author Arnaud Weber
Creates a swing applet instance.Class JApplet, void setLayout(LayoutManager)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 JComponent#getDefaultLocale
By default the layout of this component may not be set the layout of its contentPane should be set instead. For example:Class JApplet, void update(Graphics)An attempt to set the layout of this component will cause an runtime exception to be thrown. Subclasses can disable this behavior. @see #setRootPaneCheckingEnabled @exception Error if called with rootPaneChecking truethiComponentthisComponent.getContentPane().setLayout(newBorderLayoutGridLayout(1 2))
Just callspaint(g). This method was overridden to prevent anunneccessaryunnecessary call to clear the background.
An implementation of a "push" button. See How to Use Buttons Check Boxes and Radio Buttons in The Java Tutorial for information and examples of using buttons.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JButtonkey 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: An implementation of a \"push\" button. @version 1.84 0492 12/0603/0001 @author Jeff Dinkins
This class implements accessibility support for theJButtonclass. It provides an implementation of the Java Accessibility API appropriate to button user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Creates a button where properties are taken from theClass JButton, constructor JButton(String, Icon)Actionsupplied. @param a theActionused to specify the new button @since 1.3
Creates a button with initial text and an icon. @param text the text of the buttonClass JButton, void configurePropertiesFromAction(Action).@param icon the Icon image to display on the button
Factory method which sets theClass JButton, AccessibleContext getAccessibleContext()AbstractButton's properties according to values from theActioninstance. The properties which get set may differ forAbstractButtonsubclasses. By default the properties which get set areText Icon Enabled ToolTipText ActionCommandandToolTipTextMnemonic. @param a theActionfrom which to get the properties ornull@since 1.3 @see Action @see #setAction
Gets theClass JButton, String getUIClassID()AccessibleContextassociated with thisJButton. ForJButtonsJButtons theAccessibleContexttakes the form of anAccessibleJButton. A newAccessibleJButtoninstance is created if necessary. @return anAccessibleJButtonthat serves as theAccessibleContextof thisJButton@beaninfo expert: true description: The AccessibleContext associated with this Button.
Returns a string that specifies the name of the L&F class that renders this component. @return the string "ButtonUI" @see JComponent#getUIClassID @see UIDefaults#getUI @beaninfo expert: true description: A string that specifies the name of the L&F class.Class JButton, boolean isDefaultButton()
Class JButton, boolean isDefaultCapable()Returns whether orGets the valuenotof thedefaultButtonproperty which iftruemeans that this button is the current default button for itsJRootPane. Most look and feels render the default buttonondifferently and may potentially provide bindings to access theRootPanedefault button. @return"boolean"the value of thedefaultButtonproperty @see JRootPane#setDefaultButton @see #isDefaultCapable @beaninfo description: Whether or not this button is the default button
Class JButton, String paramString()ReturnsGetswhether or notthethis button isvalue of thecapabledefaultCapableofproperty.being@return thedefault buttonvalueonof theRootPane. @returndefaultCapable"boolean"property @see #setDefaultCapable @see #isDefaultButton @see JRootPane#setDefaultButton
Returns a string representation of thisClass JButton, void removeNotify()JButton. 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 benull. @return a string representation of thisJButton.
OverridesClass JButton, void setDefaultCapable(boolean)JComponent.removeNotifyto check if this button is currently set as the default button on theRootPaneand if so sets theRootPane's default button tonullto ensure theRootPanedoesn't hold onto an invalid button reference.
SetsClass JButton, void updateUI()whethertheordefaultCapablenotproperty which determines whether this button can be made the default button for its root pane. The default value of thedefaultCapableproperty istrueunless otherwise specified by the look and feel. @param defaultCapabletrueif this button will be capable of being the default button on theRootPane;.@returnotherwise"boolean"false@see #isDefaultCapable @beaninfo bound: true attribute: visualUpdate true description: Whether or not this button can be the default button
NotificationResetsfromtheUIFactoryUI property tothata value from theL&Fcurrent lookhas changedand feel. @see JComponent#updateUI
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 Use Buttonc 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see JRadioButton @beaninfo attribute: isContainer false description: A component which can be selected or deselected. @version 1.59 0468 12/0603/0001 @author Jeff Dinkins
This class implements accessibility support for theJCheckBoxclass. It provides an implementation of the Java Accessibility API appropriate to check box user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Factory method which sets theClass JCheckBox, String getUIClassID()ActionEventsource's properties according to values from the Action instance. The properties which are set may differ for subclasses. By default the properties which get set areTextandIconMnemonic Enabled ActionCommandToolTipText. @param a the Action from which to get the properties or null @since 1.3 @see Action @see #setAction
Returns a string that specifies the name of the L&F class that renders this component. @return the string "CheckBoxUI" @see JComponent#getUIClassID @see UIDefaults#getUI @beaninfo expert: true description: A string that specifies the name of the L&F classClass JCheckBox, boolean isBorderPaintedFlat()
Class JCheckBox, void setBorderPaintedFlat(boolean)ReturnsGetswhethertheborder should bevalue of thepaintedborderPaintedFlatflatproperty. @return the value of theborderPaintedFlatproperty @see #setBorderPaintedFlat
SetsClass JCheckBox, void updateUI()whethertheborderPaintedFlatproperty which gives a hint to theborder should be paintedlook and feel asflatto the appearance of the check box border. This is usually set totruewhen aJCheckBoxinstance is used as a renderer in a component such as aJTableorJTree. The default value for theborderPaintedFlatproperty isfalse. This method fires a property changed event. Some look and feels might not implement flat borders; they will ignore this property. @param biftruerequests that the borderisbe painted flat.;falserequests normal borders @see #isBorderPaintedFlat @beaninfo bound: true attribute: visualUpdate true description: Whether the border is painted flat.
NotificationResetsfromtheUIFactoryUI property tothata value from theL&Fcurrent lookhas changedand feel. @see JComponent#updateUI
A menu item that can be selected or deselected. If selected the menu item typically appears with a checkmark next to it. If unselected or deselected the menu item appears without a checkmark. Like a regular menu item a check box menu item can have either text or a graphic icon associated with it or both.Either
isSelected/setSelectedorgetState/setStatecan be used to determine/specify the menu item's selection state. The preferred methods areisSelectedandsetSelectedwhich work for all menus and buttons. ThegetStateandsetStatemethods exist for compatibility with other component sets.For further information and examples of using check box menu items 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
JCheckBoxMenuItemkey 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A menu item which can be selected or deselected. @version 1.48 0452 12/0603/0001 @author Georges Saab @author David Karlton
This class implements accessibility support for theJCheckBoxMenuItemclass. It provides an implementation of the Java Accessibility API appropriate to checkbox menu item user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Class JColorChooser, void addChooserPanel(AbstractColorChooserPanel)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.
A futureAsreleaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component that supports selecting a Color. @version 1.30 0441 12/0603/0001 @author James Gosling @author Amy Fowler @author Steve Wilson
Adds a color chooser panel to the color chooser. @param panel the AbstractColorChooserPanel to be added
Class JColorChooser, JDialog createDialog(Component, String, boolean, JColorChooser, ActionListener, ActionListener)Creates and returns a new dialog containing the specifiedClass JColorChooser, AbstractColorChooserPanel[] getChooserPanels()ColorChooser`pane along with "OK" "Cancel" and "Reset" buttons. If the "OK" or "Cancel" buttons are pressed the dialog is automatically hidden (but not disposed). If the "Reset" button is pressed the color-chooser's color will be reset to the color which was set the last timeshowwas invoked on the dialog and the dialog will remain showing. @param c the parent component for the dialog @param title the title for the dialog @param modal a boolean. When true the remainder of the program is inactive until the dialog is closed. @param chooserPane the color-chooser to be placed inside the dialog @param okListener the ActionListener invoked when "OK" is pressed @param cancelListener the ActionListener invoked when "Cancel" is pressed @return a new dialog containing the color-chooser pane @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless
Returns the specified color panels. @return an array of AbstractColorChooserPanel objects
Class JColorChooser, JComponent getPreviewPanel()Returns the preview panel that shows a chosen color. @return a JComponent object -- the preview panel
Class JColorChooser, ColorSelectionModel getSelectionModel()Returns the data model that handles color selections. @return a ColorSelectionModel object
Class JColorChooser, ColorChooserUI getUI()Returns the L&F object that renders this component. @return the ColorChooserUI object that renders this component
Class JColorChooser, AbstractColorChooserPanel removeChooserPanel(AbstractColorChooserPanel)Removes the Color Panel specified. @Class JColorChooser, void setChooserPanels(AbstractColorChooserPanel[])exception IllegalArgumentException if panel is not in list of known chooser panels @param name a string that specifies the panel to be removed @return the color panel @exception IllegalArgumentException if panel is not in list of known chooser panels
Specifies the Color Panels used to choose a color value. @param panels an array ofClass JColorChooser, void setColor(Color)AbstractColorChooserPanelobjectobjects @beaninfo bound: true hidden: true description: An array of different chooser types.
Sets the current color of the color chooser to the specified color.Class JColorChooser, void setColor(int)ThisTheColorSelectionModelwill fire aPropertyChangeEventChangeEventfor the property named "color".@param color the color to be set in the color chooser @see JComponent#addPropertyChangeListener @beaninfo bound: false hidden: false description: The current color the chooser is to display.
Sets the current color of the color chooser to the specified color. @param c anClass JColorChooser, void setSelectionModel(ColorSelectionModel)intinteger value that sets the current color in the chooser where the low-order 8 bits specify the Blue value the next 8 bits specify the Green value and the 8 bits above that specify the Red value.
Class JColorChooser, void setUI(ColorChooserUI)SetSets the model containing the selected color. @param newModel the newColorSelectionModelobject @beaninfo bound: true hidden: true description: The model which contains the currently selected color.
Sets the L&F object that renders this component. @param ui the ColorChooserUI L&F object @see UIDefaults#getUI @beaninfo bound: true hidden: true description: The UI object that implements the color chooser's LookAndFeel.
Class JColorChooser, Color showDialog(Component, String, Color)Shows a modal color-chooser dialog and blocks until the dialog is hidden. If the user presses the "OK" button then this method hides/disposes the dialog and returns the selected color. If the user presses the "Cancel" button or closes the dialog without pressing "OK" then this method hides/disposes the dialog and returnsnull. @param component the parentComponentfor the dialog @param title the String containing the dialog's title @param initialColor the initial Color set when the color-chooser is shown @return the selected color ornullif the user opted out @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless
A component that combines a button ortexteditable 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 includesaantexteditable field into which the user can type a value.For examples and information on using combo boxes see How to Use Combo Boxes 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
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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.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.
82 02112 12/0920/01 @author Arnaud Weber @author Mark Davidson
This class implements accessibility support for theJComboBoxclass. It provides an implementation of the Java Accessibility API appropriate to Combo Box user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Adds anClass JComboBox, void addItem(Object)ActionListener.The
listenerActionListenerwill receive anactionActionEventwhen a selection has been made.eventIf theusercombofinishes making abox is editableselectionthen anActionEventwill be fired when editing has stopped. @param l theActionListenerthat is to be notified @see #setSelectedItem
Adds an item to the item list. This method works only if theClass JComboBox, void addItemListener(ItemListener)JComboBoxusesthe default data model. JComboBox usesathe defaultmutable data modelwhen created with the empty constructor and no other model has been set.Warning: Focus and keyboard navigation problems may arise if you add duplicate String objects. A workaround is to add new objects instead of String objects and make sure that the toString() method is defined. For example:
comboBox.addItem(makeObj("Item 1")); comboBox.addItem(makeObj("Item 1")); ... private Object makeObj(final String item) { return new Object() { public String toString() { return item; } }; }@param anObject the Object to add to the list @see MutableComboBoxModel
Adds anClass JComboBox, void contentsChanged(ListDataEvent)ItemListener.
aListenerwill receiveanone oreventtwoItemEvents when the selected item changes. @param aListener theItemListenerthat is to be notified @see #setSelectedItem
This method is public as an implementation side effect. do not call or override.Class JComboBox, void fireActionEvent()@see javax.swing.event.ListDataListener
Notifies all listeners that have registered interest for notification on this event type. @Class JComboBox, Object getSelectedItem()param e the event of interest @see EventListenerList
Returns theClass JComboBox, Object[] getSelectedObjects()currentlycurrent selected item.@returnIf the
currentlycomboselectedbox is editable then this value may not have been added to thelist object fromcombo box withaddIteminsertItemAtor the datamodelconstructors. @return the current selected Object @see #setSelectedItem
Returns an array containing the selected item. This method is implemented for compatibility withClass JComboBox, void insertItemAt(Object, int)ItemSelectable. @returnsreturn an array ofObjectscontaining one element -- the selected item
Inserts an item into the item list at a given index. This method works only if theClass JComboBox, void intervalAdded(ListDataEvent)JComboBoxusesthe default data model. JComboBox uses theadefaultmutable data modelwhen created with the empty constructor and no other model has been set. @param anObject theObjectto add to the list @param index an integer specifying the position at which to add the item @see MutableComboBoxModel
Class JComboBox, void intervalRemoved(ListDataEvent)Invoked items have been added to the internalThis method is public as an implementation sidedata modeleffect.The "interval" includes the firstdoand last valuesnot call oradded. @see javax.swing.eventoverride.ListDataListener
Class JComboBox, boolean isFocusTraversable()Invoked when values have been removed from theThis method is public as an implementation sidedata modeleffect.The "interval" includes the firstdoand last valuesnot call orremoved. @see javax.swing.eventoverride.ListDataListener
ReturnsClass JComboBox, boolean isLightWeightPopupEnabled()true ifwhetherthethiscomponentComponentcanreceivebecome the focus. In this case thecomponentowner.returns@returnfalsetrueifit is editable so that thethisEditorComponentobjectisreceivesfocusable;thefalsefocusotherwiseinstead@seeof#setFocusablethe@sincecomponentJDK1.1 @return truedeprecatedif the componentAscan receiveofthe1.4focus elsereplaced byfalseisFocusable().
Class JComboBox, boolean isPopupVisible()Returns true if lightweightGets the value of(all-Java)thepopupslightWeightPopupEnabledare in use or false if heavyweight (native peer) popups are being usedproperty. @returntruethe valueif lightweightof thepopupslightWeightPopupEnabledarepropertyin@seeuse#setLightWeightPopupEnabled
Determines the visibility of the popup. @return true if the popup is visible otherwise returns falseClass JComboBox, void removeItem(Object)
Removes an item from the item list. This method works only if theClass JComboBox, void removeItemAt(int)JComboBoxusesthe default data model. JComboBox usesathe defaultmutable data modelwhen created with the empty constructor and no other model has been set. @param anObject the object to remove from the item list @see MutableComboBoxModel
Removes the item atClass JComboBox, boolean selectWithKeyChar(char)anIndexThis method works only if theJComboBoxusesthe default data model. JComboBox usesathe defaultmutable data modelwhen created with the empty constructor and no other model has been set. @param anIndex an int specifying theidexindex of the item to remove where 0 indicates the first item in the list @see MutableComboBoxModel
Selects the list item thatClass JComboBox, void selectedItemChanged()correpondscorresponds to the specified keyboard character and returns true if there is an item corresponding to that character. Otherwise returns false. @param keyChar a char typically this is a keyboard key typed by the user
This protected method isClass JComboBox, void setAction(Action)called when the selected itemimplementationchangesspecific.ItsDodefault implementationnotnotifies the item listenersaccess directly or override.
Sets theClass JComboBox, void setActionCommand(String)Actionfor theActionEventsource. The newActionreplaces any previously setActionbut does not affectActionListenersindependantlyindependently added withaddActionListener. If theActionis already a registeredActionListenerfor theActionEventsource it is not re-registered.A side-effect of setting the
Actionis that theActionEventsource's properties are immedately set from the values in theAction(performed by the methodconfigurePropertiesFromAction) and subsequently updated as theAction's properties change (via aPropertyChangeListenercreated by the methodcreateActionPropertyChangeListener. @param a theActionfor theJComboBoxornull. @since 1.3 @see Action @see #getAction @see #configurePropertiesFromAction @see #createActionPropertyChangeListener @beaninfo bound: true attribute: visualUpdate true description: the Action instance connected with this ActionEvent source
Sets the actionClass JComboBox, void setLightWeightPopupEnabled(boolean)commnandcommand that should be included in the event sent to action listeners. @param aCommand a string containing the "command" that is sent to action listeners; the same listener can then do different things depending on the command it receives
Class JComboBox, void setRenderer(ListCellRenderer)WhenSetsdisplayingthepopuplightWeightPopupEnabledproperty which provides a hint as to whether or not a lightweightJComboBoxComponentchooseshould be used tousecontain theJComboBoxversus alightheavyweightweightComponentpopupsuchifas aPaneloritafitsWindow.This method allows you to disableThe decision of lightweight versus heavyweightthisis ultimately up to thefeatureJComboBox.You haveLightweight windowstoare more efficient than heavyweight windows but lightweight and heavyweight components dodisable itnot mixifwell in a GUI. If your application mixeslightlightweight and heavyweight components you should disable lightweight popups. The default value for thelightWeightPopupEnabledproperty istrueunless otherwise specifiedweightby the look andheavyfeel.weightsSomecomponentslook and feels always use heavyweight popups no matter what the value of this property.See the article Mixing Heavy and Light Components on The Swing Connection This method fires a property changed event
. @param aFlag iftruelightweight popups are desired @beaninfo bound: true expert: true description:When setSet todisablesfalseusing light weightto require heavyweight popups.
Sets the renderer that paints the list items and the item selected from the list in the JComboBox field. The renderer is used if the JComboBox is not editable. If it is editable the editor is used to render and edit the selected item.Class JComboBox, void setSelectedIndex(int)The default renderer displays a string
obtained by callingorthe selected object's toStringanmethodicon. Other renderers can handle graphic images and composite items.To display the selected item
aRenderer.getListCellRendererComponentis called passing the list object and an index of -1. @param aRenderer theListCellRendererthat displays the selected item @see #setEditor @beaninfo bound: true expert: true description: The renderer that paints the item selected in the list.
Selects the item at indexClass JComboBox, void setSelectedItem(Object)anIndex. @param anIndex an integer specifying the list item to select where 0 specifies the first item in the list and -1 indicates no selection @exception IllegalArgumentException ifanIndex<-1 oranIndexis greater than or equal to size @beaninfo preferred: true description: The item at index is selected.
Sets the selected item in theClass JComboBox, void setUI(ComboBoxUI)JComboBoxcombo boxby specifyingdisplay area to the object in thelistargument. IfanObjectis in the list the display area showsanObjectselected.If
listanObjectis not in thedisplaysand the combo box is uneditable it will not change the current selection. For editable combo boxes the selection will change toanObject.If this constitutes a change in the selected item
with one or twoItemListeners added to the combo box will be notifiedItemEvents. If there is a current selected item anItemEventwill be fired and the state change will beItemEvent.DESELECTED. IfanObjectis in the list and is not currently selected then anItemEventwill be fired and the state change will beItemEvent.SELECTED.. @param anObject the list object to select; use
ActionListeners added to the combo box will be notified with anActionEventwhen this method is callednullto clear the selection @beaninfo preferred: true description: Sets the selected item in the JComboBox.
Sets the L&F object that renders this component. @param ui theClass JComboBox, void updateUI()ComboBoxUIL&F object @see UIDefaults#getUI @beaninfoexpertbound: true hidden: true attribute: visualUpdate true description: TheComboBoxUI implementationUI object thatdefinesimplements thecombo box look andComponent'sfeelLookAndFeel.
NotificationResetsfromtheUIFactoryUI property tothata value from theL&Fcurrent lookhas changedand feel. @see JComponent#updateUI
The base class for all Swing components except top-level containers. To use a component that inherits fromJComponentyou must place the component in a containment hierarchy whose root is a top-level Swing container. Top-level Swing containers -- such asJFrameJDialogandJApplet-- are specialized components that provide a place for other Swing components to paint themselves. For an explanation of containment hierarchies see Swing Components and the Containment Hierarchy a section in The Java Tutorial.The
JComponentclass provides:For more information on these subjects see the Swing package description and The Java Tutorial section The JComponent Class.
- The base class for both standard and custom components that use the Swing architecture.
- A "pluggable look and feel" (L&F) that can be specified by the programmer or (optionally) selected by the user at runtime. The look and feel for each component is provided by a UI delegate -- an object that descends from javax.swing.plaf.ComponentUI See How to Set the Look and Feel in The Java Tutorial for more information.
- Comprehensive keystroke handling. See the document Keyboard Bindings in Swing an article in The Swing Connection for more information.
- Support for tool tips -- short descriptions that pop up when the cursor lingers over a component. See How to Use Tool Tips in The Java Tutorial for more information.
- Support for accessibility.
JComponentcontains all of the methods in theAccessibleinterface but it doesn't actually implement the interface. That is the responsibility of the individual classes that extendJComponent.- Support for component-specific properties. With the #putClientProperty and #getClientProperty methods you can associate name-object pairs with any object that descends from
JComponent.- An infrastructure for painting that includes double buffering and support for borders. For more information see Painting and How to Use Borders both of which are sections 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see KeyStroke @see Action @see #setBorder @see #registerKeyboardAction @see JOptionPane @see #setDebugGraphicsOptions @see #setToolTipText @see #setAutoscrolls @version 2.130 07/09/99 @author Hans Muller @author Arnaud Weber
Inner class of JComponent used to provide default support for accessibility. This class is not meant to be used directly by application developers but is instead meant only to be subclassed by component developers.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
DefaultClass JComponent, void addAncestorListener(AncestorListener)JComponentconstructor. This constructor doesnovery little initialization beyond calling theContainerconstructor. For example the initial layout manager isnull. It does however set the component's locale property to the value returned byJComponent.getDefaultLocale. @see #getDefaultLocale
RegistersClass JComponent, void addNotify()listenerso that it will receiveAncestorEventswhen it or any of its ancestors move or are made visible/or invisible. Events are also sent when the component or its ancestors are added or removed from the containment hierarchy. @param listener theAncestorListenerto register @see AncestorEvent
Notifies this component that it now has a parent component. When this method is invoked the chain of parent components is set up with KeyboardAction event listeners. @see #registerKeyboardAction
Class JComponent, void addPropertyChangeListener(PropertyChangeListener)Adds aClass JComponent, void addPropertyChangeListener(String, PropertyChangeListener)PropertyChangeListenerto the listener list. The listener is registered for all properties.A
PropertyChangeEventwill get fired in response to setting a bound property such assetFontsetBackgroundorsetForeground.Note that if the current component is inheriting its foreground background or font from its container then no event will be fired in response to a change in the inherited property. @param listener the
PropertyChangeListenerto be added
Adds aClass JComponent, void addVetoableChangeListener(VetoableChangeListener)PropertyChangeListenerfor a specific property. The listener will be invoked only when a call onfirePropertyChangenames that specific property.If listener is
nullno exception is thrown and no action is performed. @param propertyName the name of the property to listen on @param listener thePropertyChangeListenerto be added
Adds aClass JComponent, void computeVisibleRect(Rectangle)VetoableChangeListenerto the listener list. The listener is registered for all properties. @param listener theVetoableChangeListenerto be added
Returns theClass JComponent, boolean contains(int, int)Component's "visible rect rectangle" - the intersection of the visible rectangles for this component and all of its ancestors. The return value is stored invisibleRect. @param visibleRect aRectanglecomputed as the intersection of all visible rectangles for this component and all of its ancestors -- this is the return value for this method @see #getVisibleRect
Gives the UI delegate an opportunity to define the precise shape of this component for the sake of mouse processing. @return true if this component logically contains x y @see java.awt.Component#contains(int int) @see ComponentUIClass JComponent, JToolTip createToolTip()
Returns the instance ofClass JComponent, void disable()JToolTipthat should be used to display the tooltip. Components typically would not override this method but it can be used to cause different tooltips to be displayed differently. @return theJToolTipused to display this toolTip
Class JComponent, void enable()overriddenOverridden to ensureAccessibilitysupport. Please use {@alink java.awt.Component.setEnable(boolean)}.
Class JComponent, void firePropertyChange(String, Object, Object)overriddenOverridden to ensureAccessibilitysupport. Please use {@alink java.awt.Component.setEnable(boolean)}.
Supports reporting bound property changes. IfClass JComponent, void firePropertyChange(String, boolean, boolean)oldValueandnewValueare not equal and thePropertyChangeEventlistener list isn't empty then fire aPropertyChangeevent to each listener. This method has an overloaded method for each primitive type. For example here's how to write a bound property set method whose value is anintinteger:public void setFoo(int newValue) { int oldValue = foo; foo = newValue; firePropertyChange("foo" oldValue newValue); }@param propertyName the programmatic name of the property that was changed @param oldValue the old value of the property (as an Object) @param newValue the new value of the property (as an Object) @see java.beans.PropertyChangeSupport
Reports a bound property change. @param propertyName the programmatic name of the property that was changed @param oldValue the old value of the property (as a boolean) @param oldValue the old value of the property (as a boolean) @see #firePropertyChange(java.lang.String java.lang.Object java.lang.Object)Class JComponent, void firePropertyChange(String, byte, byte)
Reports a bound property change. @param propertyName the programmatic name of the property that was changed @param oldValue the old value of the property (as a byte) @param newValue the new value of the property (as a byte) @see #firePropertyChange(java.lang.String java.lang.Object java.lang.Object)Class JComponent, void firePropertyChange(String, char, char)
Reports a bound property change. @param propertyName the programmatic name of the property that was changed @param oldValue the old value of the property (as a char) @param newValue the new value of the property (as a char) @see #firePropertyChange(java.lang.String java.lang.Object java.lang.Object)Class JComponent, void firePropertyChange(String, double, double)
Reports a bound property change. @param propertyName the programmatic name of the property that was changed @param oldValue the old value of the property (as a double) @param newValue the new value of the property (as a double) @see #firePropertyChange(java.lang.String java.lang.Object java.lang.Object)Class JComponent, void firePropertyChange(String, float, float)
Reports a bound property change. @param propertyName the programmatic name of the property that was changed @param oldValue the old value of the property (as a float) @param newValue the new value of the property (as a float) @see #firePropertyChange(java.lang.String java.lang.Object java.lang.Object)Class JComponent, void firePropertyChange(String, int, int)
Reports a bound property change. @param propertyName the programmatic name of the property that was changed @param oldValue the old value of the property (as an int) @param newValue the new value of the property (as an int) @see #firePropertyChange(java.lang.String java.lang.Object java.lang.Object)Class JComponent, void firePropertyChange(String, long, long)
Reports a bound property change. @param propertyName the programmatic name of the property that was changed @param oldValue the old value of the property (as a long) @param newValue the new value of the property (as a long) @see #firePropertyChange(java.lang.String java.lang.Object java.lang.Object)Class JComponent, void firePropertyChange(String, short, short)
Reports a bound property change. @param propertyName the programmatic name of the property that was changed @param oldValue the old value of the property (as a short) @param newValue the old value of the property (as a short) @see #firePropertyChange(java.lang.String java.lang.Object java.lang.Object)Class JComponent, void fireVetoableChange(String, Object, Object)
Supports reporting constrained property changes. This method can be called when a constrained property has changed and it will send the appropriateClass JComponent, AccessibleContext getAccessibleContext()PropertyChangeEventto any registeredVetoableChangeListeners. @param propertyName the name of the property that was listened on @param oldValue the old value of the property @param newValue the new value of the property @exception PropertyVetoException when the attempt to set the property is vetoed by thereceiver.component
Class JComponent, ActionListener getActionForKeyStroke(KeyStroke)GetsReturns theAccessibleContextassociated with thisJComponent. The method implemented by this base class returns null. Classes that extendJComponentshould implement this method to return theAccessibleContextassociated with the subclass. @return theAccessibleContextof thisJComponent
Returns the object that will perform the action registered for a given keystroke. @return the ActionListener object invoked when the keystroke occurs
Class JComponent, ActionMap getActionMap()Returns theClass JComponent, float getAlignmentX()ActionMapused to determine whatActionto fire for particularKeyStrokebinding. The returnedActionMapunless otherwise set will have theActionMapfrom the UI set as the parent. @return theActionMapcontaining the key/action bindings @since 1.3
OverridesClass JComponent, float getAlignmentY()Container.getAlignmentXto return the vertical alignment. @return the value of thealignmentXproperty @see #setAlignmentX @see java.awt.Component#getAlignmentX
OverridesClass JComponent, boolean getAutoscrolls()Container.getAlignmentYto return the horizontal alignment. @return the value of thealignmentYproperty @see #setAlignmentY @see java.awt.Component#getAlignmentY
Class JComponent, Border getBorder()ReturnsGetstruetheifautoscrollsthis component automatically scrolls its contents when dragged (when contained inproperty.a@returncomponent that supports scrollingthe value of thelikeautoscrollsJViewport).property @see JViewport @see #setAutoscrolls
Returns the border of this component or null if no border is currently set. @return the border object for this component @see #setBorder
Class JComponent, Rectangle getBounds(Rectangle)Stores the bounds of this component into "return value"Class JComponent, Object getClientProperty(Object)rvand returnsrv. Ifrvisnulla newRectangleis allocated. This version ofgetBoundsis useful if the caller wants to avoid allocating a new()Rectangleobject on the heap. @param rv the return value modified to the component's bounds @returnrv; ifrvisnullreturn a newly createdRectanglewith this component's bounds
Returns the value of the property with the specified key. Only properties added withClass JComponent, Graphics getComponentGraphics(Graphics)putClientPropertywill return a non-nullvalue. @param key the being queried @return the value of this property ornull@see #putClientProperty
Returns the graphics object used to paint this component. IfClass JComponent, int getConditionForKeyStroke(KeyStroke)DebugGraphicsis turned on we create a newDebugGraphicsobject if necessary. Otherwise we just configure the specified graphics object's foreground and font. @param g the originalGraphicsobject @return aGraphicsobject configured for this component
Returns the condition that determines whether a registered action occurs in response to the specified keystroke.Class JComponent, int getDebugGraphicsOptions()For Java 2 platform v1.3 a
KeyStrokecan be associated with more than one condition. For example 'a' could be bound for the two conditionsWHEN_FOCUSEDandWHEN_IN_FOCUSED_WINDOWcondition. @return the action-keystroke condition
Returns the state of graphics debugging. @return a bitwise OR'd flag of zero or more of the following options:Class JComponent, Graphics getGraphics()@see #setDebugGraphicsOptions
- DebugGraphics.LOG_OPTION - causes a text message to be printed.
- DebugGraphics.FLASH_OPTION - causes the drawing to flash several times.
- DebugGraphics.BUFFERED_OPTION - creates an
ExternalWindowthat displays the operations performed on the View's offscreen buffer.- DebugGraphics.NONE_OPTION disables debugging.
- A value of 0 causes no changes to the debugging options.
Returns this component's graphics context which lets you draw on a component. Use this method get aClass JComponent, int getHeight()Graphicsobject and then invokeoeprationsoperations on that object to draw on the component. @return this components graphics context
Returns the current height of this component. This method is preferable to writingClass JComponent, InputMap getInputMap()component.getBounds().heightorcomponent.getSize().heightbecause it doesn't cause any heap allocations. @return the current height of this component.
Returns theClass JComponent, InputMap getInputMap(int)InputMapthat is used when thereceivercomponent has focus. This is convenience method forgetInputMap(WHEN_FOCUSED). @return theInputMapused when the component has focus @since JDK1.3
Returns theClass JComponent, InputVerifier getInputVerifier()InputMapthat is used duringcondition. @param condition one of WHEN_IN_FOCUSED_WINDOW WHEN_FOCUSED WHEN_ANCESTOR_OF_FOCUSED_COMPONENT @return theInputMapfor the specifiedcondition@since 1.3
Returns the input verifier for this component. @return the inputVerifier property @since 1.3 @see InputVerifier
Class JComponent, Insets getInsets()If a border has been set on this component returns the border's insets; otherwise calls super.getInsets. @return the value of the insets property @see #setBorder
Class JComponent, Insets getInsets(Insets)Returns anClass JComponent, EventListener[] getListeners(Class)Insetsobject containing this component's inset values. The passed-inInsetsobject will be reused if possible. Calling methods cannot assume that the same object will be returned however. All existing values within this object are overwritten. Ifinsetsis null this will allocate a new one. @param insets theInsetsobject which can be reused @return theInsetsobject @see #getInsets @beaninfo expert: true
Class JComponent, Point getLocation(Point)ReturnReturns an array of all thelistenersobjectsthat werecurrently registeredaddedasFooListenerstoupon thisJComponent.withaddXXXListener()FooListenerswhere XXX isare registered using thenameaddFooListenerofmethod.You can specify the
listenerTypeargument with a class literal such asFooListener.class. For exampleto get all ofyou can query atheJComponentMouseListenerscforthe given Componentits mouse listenerscwithone would writethe following code:If no suchMouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));listenerlisteners existlist exists thenthis method returns an empty array. @param listenerType the type of listeners requested; thisisparameterreturnedshould specify an interface that descends fromjava.util.EventListener @returns allreturn an array ofthe listenersall objectsforregistered asFooListeners on thisJComponentcomponent or an empty array if no such listeners have been added @exception ClassCastException iflistenerTypedoesn't specify a class or interface that implementsjava.util.EventListener @since 1.3 @see #getVetoableChangeListeners @see #getAncestorListeners
Stores the x y origin of this component into "return value"Class JComponent, Dimension getMaximumSize()rvand returnsrv. Ifrvisnulla newPointis allocated. This version ofgetLocationis useful if the caller wants to avoid allocating a new()Pointobject on the heap. @param rv the return value modified to the component's location @returnrv
If the maximum size has been set to a non-Class JComponent, Dimension getMinimumSize()nullvalue just returns it. If the UI delegate'sgetMaximumSizemethod returns a non()-null value then return that; otherwise defer to the component's layout manager. @return the value of themaximumSizeproperty.@see #setMaximumSize @see ComponentUI
If the minimum size has been set to a non-Class JComponent, Component getNextFocusableComponent()nullvalue just returns it. If the UI delegate'sgetMinimumSizemethod returns a non-()nullvalue then return that; otherwise defer to the component's layout manager. @return the value of theminimumSizeproperty @see #setMinimumSize @see ComponentUI
Returns theClass JComponent, Dimension getPreferredSize()nextComponentfocusable componentset by a prior call tosetNextFocusableComponent(Component)on thisJComponent. @return theComponentthat will follow thisJComponentin the focus traversal cycle ornullifthe focus manager should choosenone has been explicitly specifiedthe@see #setNextFocusableComponentnext@deprecated As of 1.4focusable componentreplaced byautomaticallyFocusTraversalPolicy.
If theClass JComponent, KeyStroke[] getRegisteredKeyStrokes()preferredSizehas been set to a non-nullvalue just returns it. If the UI delegate'sgetPreferredSizemethod returns a non()nullvalue then return that; otherwise defer to the component's layout manager. @return the value of thepreferredSizeproperty @see #setPreferredSize @see ComponentUI
Returns theClass JComponent, JRootPane getRootPane()KeyStrokesthat will initiate registered actions. @return an array ofKeyStrokeobjects @see #registerKeyboardAction
Returns theClass JComponent, Dimension getSize(Dimension)JRootPaneancestor forathis component. @return theJRootPanethat contains this component ornullif noJRootPaneis found
Stores the width/height of this component into "return value"Class JComponent, Point getToolTipLocation(MouseEvent)rvand returnsrv. Ifrvisnulla newDimensionobject is allocated. This version ofgetSizeis useful if the caller wants to avoid allocating a new()Dimensionobject on the heap. @param rv the return value modified to the component's size @returnrv
Returns the tooltip location in this component's coordinate system. IfClass JComponent, String getToolTipText()nullis returned Swing will choose a location. The default implementation returnsnull. @param event theMouseEventthat caused theToolTipManagerto show the tooltip @return always returnsnull
Returns the tooltip string that has been set with setToolTipText(). @return the text of the tool tip @see #TOOL_TIP_TEXT_KEY
Class JComponent, String getToolTipText(MouseEvent)Returns the string to be used as the tooltip for event. By default this returns any string set using setToolTipText(). If a component provides more extensive API to support differing tooltips at different locations this method should be overridden.
Class JComponent, Container getTopLevelAncestor()Returns the top-level ancestor of this component (either the containingClass JComponent, String getUIClassID()WindoworApplet) ornullif this component has not been added to any container. @return the top-levelContainerthat this component is in ornullif not in any container
Returns theClass JComponent, boolean getVerifyInputWhenFocusTarget()UIDefaultskey used to look up the name of theswing.plaf.ComponentUIclass that defines the look and feel for this component. Most applications will never need to call this method. Subclasses ofJComponentthat support pluggable look and feel should override this method to return aUIDefaultskey that maps to theComponentUIsubclass that defines their look and feel. @returnThetheUIDefaultskey for aComponentUIsubclass.@see UIDefaults#getUI @beaninfo expert: true description: UIClassID
Class JComponent, Rectangle getVisibleRect()GetReturns the value that indicates whether the input verifier for the current focus owner will be called before this component requests focus. @return value of theverifyInputWhenFocusTargetproperty @see InputVerifier @see #setInputVerifier @see #getInputVerifier @see #setVerifyInputWhenFocusTarget @since 1.3
Returns theClass JComponent, int getWidth()Component's "visible rectangle" - the intersection of this component's visible rectangle:new Rectangle(0 0 getWidth() getHeight());and all of its ancestors' visibleRectanglesrectangles. @return the visible rectangle
Returns the current width of this component. This method is preferable to writingClass JComponent, int getX()component.getBounds().widthorcomponent.getSize().widthbecause it doesn't cause any heap allocations. @return the current width of this component.
Returns the current x coordinate of the component's origin. This method is preferable to writingClass JComponent, int getY()component.getBounds().xorcomponent.getLocation().xbecause it doesn't cause any heap allocations. @return the current x coordinate of the component's origin
Returns the current y coordinate of the component's origin. This method is preferable to writingClass JComponent, void grabFocus()component.getBounds().yorcomponent.getLocation().ybecause it doesn't cause any heap allocations. @return the current y coordinate of the component's origin
Class JComponent, boolean hasFocus()SetsRequests that this Component get the input focusonand that this Component's top-level ancestor become thereceivingfocused Window. This componentif itmust bedoesn'tdisplayablealready havevisible anditfocusable for the request to be granted.This method is intended for use by focus
managersimplementations.YouClientrarely want to callcode should not use this method; instead it should userequestFocus(). @see #requestFocus()instead
ReturnsClass JComponent, boolean isDoubleBuffered()trueif thisComponenthasis thekeyboardfocus owner. This method is obsolete and has been replaced byisFocusOwner(). @returntrueif thisComponenthasis thekeyboardfocus owner;falseotherwise @since 1.2
Returns whetherClass JComponent, boolean isFocusTraversable()thethisreceivingcomponent should use a buffer to paint. @return true if this component is double buffered otherwise false
Class JComponent, boolean isLightweightComponent(Component)IdentifiesReturns whetheror notthiscomponentComponentcanreceivebecome the focus owner.A@returndisabledtruebutton forif thisexampleComponentwouldisreturnfocusable;falseotherwise @.returnseetrue#setFocusableif@sincethisJDK1.1component@deprecatedcan receiveAs ofthe1.4focusreplaced byisFocusable().
Returns true if this component isClass JComponent, boolean isManagingFocus()alightweight that is if it doesn't have a native window system peer. @return true if this component isalightweight
Class JComponent, boolean isMaximumSizeSet()OverrideChanges thismethod and return true if yourJComponent's focusmanages focus. If your component manages focus themanager will handletraversal keys toyourCTRL+TABcomponent'sandchildrenCTRL+SHIFT+TAB.All keyAlso preventseventSortingFocusTraversalPolicywill be sent to your key listener including TAB andfrom considering descendants of this JComponent when computing a focusSHIFT+TABtraversal cycle.CONTROL+TAB@seeandjava.awt.Component#setFocusTraversalKeysCONTROL+SHIFT+TAB@seewillSortingFocusTraversalPolicymove@deprecatedthe focusAs ofto1.4the nextreplaced byorComponent.setFocusTraversalKeys(int Set)previousandcomponentContainer.setFocusCycleRoot(boolean).
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
Returns true if the minimum size has been set to a non-Class JComponent, boolean isOptimizedDrawingEnabled()nullvalue otherwise returns false. @return true ifminimumSizeis non-nullfalse otherwise
Returns true if this component tiles its children -- that is if it can guarantee that the children will not overlap. The repainting system is substantially more efficient in this common case.Class JComponent, boolean isPaintingTile()JComponentsubclasses that can't make this guarantee such asJLayeredPaneshould override this method to return false. @returntrue if this component's childrenalwaysdon'treturnsoverlaptrue
Returns true if theClass JComponent, boolean isPreferredSizeSet()receivingcomponent is currently painting a tile. If this method returns true paint will be called again for another tile. This method returns false if you are not painting a tile or if the last tile is painted. Use this method to keep some state you might need between tiles. @return true if the component is currently painting a tile false otherwise
Returns true if the preferred size has been set to a non-Class JComponent, boolean isRequestFocusEnabled()nullvalue otherwise returns false. @return true ifpreferredSizeis non-nullfalse otherwise
ReturnsClass JComponent, boolean isValidateRoot()whethertruethe receivingif thiscomponent canJComponentobtain theshould get focus;by callingotherwise returnsrequestFocusfalse. @returntrueif this component should get focus otherwise returnsfalse@see #setRequestFocusEnabled @see Focus Specification @see java.awt.Component#isFocusable
If this method returns trueClass JComponent, void paint(Graphics)revalidatecalls by descendants of this component will cause the entire tree beginning with this root to be validated. Returns false by default.()JScrollPaneoverrides this method and returns true. @return always returns false @see #revalidate @see java.awt.Component#invalidate @see java.awt.Container#validate
Class JComponent, void paintBorder(Graphics)This method isInvokedinvokedby Swing to draw components. Applications should not invokepaintdirectly but should instead use therepaintmethod to schedule the component for redrawing.This method actually delegates the work of painting to three protected methods:
paintComponentpaintBorderandpaintChildren. They're called in the order listed to ensure that children appear on top of component itself. Generally speaking the component and its children should not paint in the insets area allocated to the border. Subclasses can just override this method as always. A subclass that just wants to specialize the UI (look and feel) delegate'spaintmethod should just overridepaintComponent. @param g theGraphicscontext in which to paint @see #paintComponent @see #paintBorder @see #paintChildren @see #getComponentGraphics @see #repaint
Paints the component's border.Class JComponent, void paintChildren(Graphics)If you override this in a subclass you should not make permanent changes to the passed in
Graphics. For example you should not alter the clipRectangleor modify the transform. If you need to do these operations you may find it easier to create a newGraphicsfrom the passed inGraphicsand manipulate it. @param g theGraphicscontext in which to paint @see #paint @see #setBorder
Paints this component's children. IfClass JComponent, void paintComponent(Graphics)shouldUseBufferis true no component ancestor has a buffer and the component children can use a buffer if they have one. Otherwise one ancestor has a buffer currently in use and children should not use a buffer to paint. @param g theGraphicscontext in which to paint @see #paint @see java.awt.Container#paint
Class JComponent, void paintImmediately(Rectangle)IfCalls the UI delegate'sispaintnon-nullmethodcalls its paintif the UImethoddelegate is non-null. We pass the delegate a copy of theGraphicsobject to protect the rest of the paint code from irrevocable changes (for exampleGraphics.translate).()If you override this in a subclass you should not make permanent changes to the passed in
Graphics. For example you should not alter the clipRectangleor modify the transform. If you need to do these operations you may find it easier to create a newGraphicsfrom the passed inGraphicsand manipulate it. Further if you do not invoker super's implementation you must honor the opaque property that is if this component is opaque you must completely fill in the background in a non-opaque color. If you do not honor the opaque property you will likely see visual artifacts. @param g theGraphicsobject to protect @see #paint @see ComponentUI
Paints the specified region now. @param r a Rectangle containing the region to be painted
Class JComponent, void paintImmediately(int, int, int, int)Paints the specified region in this component and all of its descendants that overlap the region immediately.Class JComponent, String paramString()It's rarely necessary to call this method. In most cases it's more efficient to call repaint which defers the actual painting and can collapse redundant requests into a single paint call. This method is useful if one needs to update the display while the current event is being dispatched. @param x the x value of the region to be painted @param y the y value of the region to be painted @param w the width of the region to be painted @param h the height of the region to be painted @see #repaint
Returns a string representation of thisClass JComponent, void print(Graphics)JComponent. 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 benull. @return a string representation of thisJComponent
Invoke this method to print theClass JComponent, void printAll(Graphics)receivercomponent. This method will result in invocations toprintComponentprintBorderandprintChildren. It is not recommended that you override this method instead override one of the previouslymetionedmentioned methods. This method sets thereceiverscomponent's state such that the double buffer will not be used eg painting will be done directly on the passed inGraphics. @param g theGraphicscontext in which to paint @see #printComponent @see #printBorder @see #printChildren
Invoke this method to print theClass JComponent, void printBorder(Graphics)receivercomponent. This method invokesreceivercomponent. @param g theGraphicscontext in which to paint @see #print @see #printComponent @see #printBorder @see #printChildren
Prints the component's border. This is implemented to invokeClass JComponent, void printChildren(Graphics)paintBorderon thereceivercomponent.OverridesOverride this if you wish to print the border differently that it is painted. @param g theGraphicscontext in which to paint @see #print @since 1.3
Prints this component's children. This is implemented to invokeClass JComponent, void printComponent(Graphics)paintChildrenon thereceivercomponent. Override this if you wish to print the children differently than painting. @param g theGraphicscontext in which to paint @see #print @since 1.3
This is invoked during a printing operation. This is implemented to invokeClass JComponent, boolean processKeyBinding(KeyStroke, KeyEvent, int, boolean)paintComponenton thereceivercomponent. Override this if you wish to add special painting behavior when printing. @param g theGraphicscontext in which to paint @see #print @since 1.3
Invoked to process the key bindings forClass JComponent, void processKeyEvent(KeyEvent)ksas the result of theKeyEvente. This obtains the appropriateInputMapgets the binding gets the action from theActionMapand then (if the action is found and thereceivercomponent is enabled) invokesnotifyActionto notify the action. @param ks theKeyStrokequeried @param e theKeyEvent@param condition one of the following values:@param pressed true if the key is pressed @return true if there was a binding to an action and the action was enabled @since 1.3
- JComponent.WHEN_FOCUSED
- JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
- JComponent.WHEN_IN_FOCUSED_WINDOW
Overrides processKeyEvent to process events.
Class JComponent, void putClientProperty(Object, Object)Adds an arbitrary key/value "client property" to this component.Class JComponent, void registerKeyboardAction(ActionListener, String, KeyStroke, int)The
get/putClientPropertymethods provide access to a small per-instance hashtable. Callers can use get/putClientProperty to annotate components that were created by another module. For example a layout manager might store per child constraints this way. For example:componentA.putClientProperty("to the left of" componentB);If value isnullthis method will remove the property. Changes to client properties are reported withPropertyChangeevents. The name of the property (for the sake of PropertyChange events) iskey.toString().The
clientPropertydictionary is not intended to support large scale extensions to JComponent nor should be it considered an alternative to subclassing when designing a new component. @param key the new client property key @param value the new client property value; ifnullthis method will remove the property @see #getClientProperty @see #addPropertyChangeListener
This method is now obsolete please use a combination ofClass JComponent, void removeAncestorListener(AncestorListener)getActionMap()andgetInputMap()for similiar behavior. For example to bind theKeyStrokeaKeyStroketo theActionanActionnow use:component.getInputMap().put(aKeyStroke aCommand); component.getActionMap().put(aCommmand anAction);The above assumes you want the binding to be applicable forWHEN_FOCUSED. To register bindings for other focus states use thegetInputMapmethod that takes an integer.Register a new keyboard action.
anActionwill be invoked if a key event matchingaKeyStrokeoccurs andaConditionis verified. TheKeyStrokeobject defines a particular combination of a keyboard key and one or more modifiers (alt shift ctrl meta).The
aCommandwill be set in the delivered event if specified.The
ConditionaConditioncan be one of:
- WHEN_FOCUSED
- The action will be invoked only when the keystroke occurs while the component has the focus.
- WHEN_IN_FOCUSED_WINDOW
- The action will be invoked when the keystroke occurs while the component has the focus or if the component is in the window that has the focus. Note that the component need not be an immediate descendent of the window -- it can be anywhere in the window's containment hierarchy. In other words whenever any component in the window has the focus the action registered with this component is invoked.
- WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
- The action will be invoked when the keystroke occurs while the component has the focus or if the component is an ancestor of the component that has the focus.
The combination of keystrokes and conditions lets you define high level (semantic) action events for a specified keystroke+modifier combination (using the KeyStroke class) and direct to a parent or child of a component that has the focus or to the component itself. In other words in any hierarchical structure of components an arbitrary key-combination can be immediately directed to the appropriate component in the hierarchy and cause a specific method to be invoked (usually by way of adapter objects).
If an action has already been registered for the receiving container with the same charCode and the same modifiers
anActionwill replace the action. @param anAction theActionto be registered @param aCommand the command to be set in the delivered event @param aKeyStroke theKeyStroketo bind to the action @param aCondition the condition that needs to be met see above @see KeyStroke
UnregistersClass JComponent, void removeNotify()listenerso that it will no longer receiveAncestorEvents. @param listener theAncestorListenerto be removed @see #addAncestorListener
Notifies this component that it no longer has a parent component. When this method is invoked anyClass JComponent, void removePropertyChangeListener(PropertyChangeListener)KeyboardActionsKeyboardActions set up in the the chain of parent components are removed. @see #registerKeyboardAction
Removes aClass JComponent, void removePropertyChangeListener(String, PropertyChangeListener)PropertyChangeListenerfrom the listener list. This removes aPropertyChangeListenerthat was registered for all properties. @param listener thePropertyChangeListenerto be removed
Removes aClass JComponent, void removeVetoableChangeListener(VetoableChangeListener)PropertyChangeListenerfor a specific property. If listener isnullno exception is thrown and no action is performed. @param propertyName the name of the property that was listened on @param listener thePropertyChangeListenerto be removed
Removes aClass JComponent, void repaint(Rectangle)VetoableChangeListenerfrom the listener list. This removes aVetoableChangeListenerthat was registered for all properties. @param listener theVetoableChangeListenerto be removed
Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched. @param r a Rectangle containing the dirty region @see java.awt.Component#isShowing @see RepaintManager#addDirtyRegion
Class JComponent, void repaint(long, int, int, int, int)Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched. @param tm this parameter is not used @param x the x value of the dirty region @param y the y value of the dirty region @param width the width of the dirty region @param height the height of the dirty region @see java.awt.Component#isShowing @see RepaintManager#addDirtyRegionClass JComponent, boolean requestDefaultFocus()
RequestsClass JComponent, void resetKeyboardActions()thefocusfor theon thiscomponentJComponent'sFocusTraversalPolicy'sthatdefaultshouldComponent.have theIf thisfocusJComponentbyisdefault.aThe default implementation will recursivelyfocus cycle root then itsrequestFocusTraversalPolicytheisfocusused.onOtherwise thefirstFocusTraversalPolicycomponent thatof thisisJComponent's focus-traversable.cycle-root@returnancestorfalseisifused.the@seefocusjava.awt.FocusTraversalPolicy#getDefaultComponenthas@deprecatednot beenAs ofset1.4otherwise returnreplaced bytrueFocusTraversalPolicy.getDefaultComponent(Container).requestFocus()
Unregisters all the bindings in the first tierClass JComponent, void reshape(int, int, int, int)InputMapsandActionMap. This has the effect of removing any local bindings and allowing the bindings defined in parentInputMap/ActionMaps(the UI is usually defined in the second tier) to persist.
Moves and resizes this component. @param x the new horizontal location @param y the new vertical location @param w the new width @param h the new height @see java.awt.Component#setBoundsClass JComponent, void revalidate()
Supports deferred automatic layout.Class JComponent, void scrollRectToVisible(Rectangle)Calls
invalidateand then adds this component's()validateRootto a list of components that need to be validated. Validation will occur after all currently pending events have been dispatched. In other words after this method is called the first validateRoot (if any) found when walking up the containment hierarchy of this component will be validated. By defaultJRootPaneJScrollPaneandJTextFieldreturn true fromisValidateRoot.This method will automatically be called on this component when a property value changes such that size location or internal layout of this component has been affected. This automatic updating differs from the AWT because programs generally no longer need to invoke
validateto get the contents of the GUI to update.()@see java.awt.Component#invalidate @see java.awt.Container#validate @see #isValidateRoot @see RepaintManager#addInvalidComponent
Forwards theClass JComponent, void setActionMap(ActionMap)scrollRectToVisible()message to theJComponent's parent. Components that can service the request such asJViewportoverride this method and perform the scrolling. @param aRect the visibleRectangle@see JViewport
Sets theClass JComponent, void setAlignmentX(float)ActionMaptoam. This does not set the parent of theamto be theActionMapfrom the UI (if there was one) it is up to the caller to have done this. @param am the newActionMap@since 1.3
Sets the the vertical alignment. @param alignmentX the new vertical alignment @see #getAlignmentX @beaninfo description: The preferred horizontal alignment of the component.Class JComponent, void setAlignmentY(float)
Sets the the horizontal alignment. @param alignmentY the new horizontal alignment @see #getAlignmentY @beaninfo description: The preferred vertical alignment of the component.Class JComponent, void setAutoscrolls(boolean)
Sets theClass JComponent, void setBackground(Color)autoscrollsproperty. Iftruethis component will automatically scroll its contentsmouse dragged events will be synthetically generated when the mouse is draggedifoutside of the component's bounds and mouse motion has paused (while the button continues to be held down). The synthetic events make it appear that the drag gesture has resumed in the direction established whencontainedthe component's boundary was crossed. Components that support autoscrolling must handlemouseDraggedevents by callingscrollRectToVisiblewith a rectangle that contains the mouse event's location. All of the Swing components that support item selection and are typically displayed in aJScrollPane(JTableJListJTreeJTextAreaandJEditorPane) already handle mouse dragged events in this way. To enable autoscrolling in any other component add a mouse motion listener thatsupportscallsscrollRectToVisible.scrolling such asFor example givenJViewportaJPanelmyPanel:MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { Rectangle r = new Rectangle(e.getX() e.getY() 1 1); ((JPanel)e.getSource()).scrollRectToVisible(r); } }; myPanel.addMouseMotionListener(doScrollRectToVisible);The default value of theautoScrollsproperty isfalse. @seeparamJViewportautoscrolls if true synthetic mouse dragged events are generated when the mouse is dragged outside of a component's bounds and the mouse button continues to be held down; otherwise false @see #getAutoscrolls @see JViewport @see JScrollPane @beaninfo expert: true description:WhetherDetermines if this component automatically scrolls its contents when dragged.
Sets the background color of this component. @param bg the desired background Color @see java.awt.Component#getBackground @beaninfo preferred: true bound: true attribute: visualUpdate true description: The background color of the component.
Class JComponent, void setBorder(Border)Sets the border of this component. TheClass JComponent, void setDebugGraphicsOptions(int)Borderobject is responsible for defining the insets for the component (overriding any insets set directly on the component) and for optionally rendering any border decorations within the bounds of those insets. Borders should be used (rather than insets) for creating both decorative and non-decorative (such as margins and padding) regions for a swing component. Compound borders can be used to nest multiple borders within a single component.This is a bound property. @param border the border to be rendered for this component @see Border @see CompoundBorder @beaninfo bound: true preferred: true attribute: visualUpdate true description: The component's border.
Enables or disables diagnostic information about every graphics operation performed within the component or one of its children.Class JComponent, void setDoubleBuffered(boolean)The value of@param debugOptions determines how the component should displaythisthe information; one of the following options:
- DebugGraphics.LOG_OPTION - causes a text message to be printed.
- DebugGraphics.FLASH_OPTION - causes the drawing to flash several times.
- DebugGraphics.BUFFERED_OPTION - creates an
ExternalWindowthat displays the operations performed on the View's offscreen buffer.debug is bitwise OR'd into the current value.- DebugGraphics.NONE_OPTION disables debugging.
- A value of 0 causes no changes to the debugging options.
debugOptionsis bitwise OR'd into the current value @beaninfo preferred: true enum: NONE_OPTION DebugGraphics.NONE_OPTION LOG_OPTION DebugGraphics.LOG_OPTION FLASH_OPTION DebugGraphics.FLASH_OPTION BUFFERED_OPTION DebugGraphics.BUFFERED_OPTION description: Diagnostic options for graphics operations.
Sets whether theClass JComponent, void setEnabled(boolean)receivingthis component should use a buffer to paint. If set to true all the drawing from this component will be done in an offscreen painting buffer. The offscreen painting buffer will the be copied onto the screen.Swing'sSwings painting system alwaysuseuses a maximum of one double buffer. If aComponentis buffered and one of its ancestor is also buffered the ancestor buffer will be used. @param aFlag if true set this component to be double buffered
Sets whether or not this component is enabled. A component that is enabled may respond to user input while a component that is not enabled cannot respond to user input. Some components may alter their visual representation when they are disabled in order to provide feedback to the user that they cannot take input.Class JComponent, void setFont(Font)Note: Disabling a component does not disable it's children.
Note: Disabling a lightweight component does not prevent it from receiving MouseEvents. @param enabled true if this component should be enabled false otherwise
@see java.awt.Component#isEnabled @see java.awt.Component#isLightweight @beaninfo preferred: true bound: true attribute: visualUpdate true description: The enabled state of the component.
Sets the font for this component. @param the desired Font for this component @see java.awt.Component#getFont @beaninfo preferred: true bound: true attribute: visualUpdate true description: The font for the component.
Class JComponent, void setForeground(Color)Sets the foreground color of this component. @param fg the desired foreground Color @see java.awt.Component#getForeground @beaninfo preferred: true bound: true attribute: visualUpdate true description: The foreground color of the component.
Class JComponent, void setInputMap(int, InputMap)Sets theClass JComponent, void setInputVerifier(InputVerifier)InputMapto use under the conditionconditiontomap. Anullvalue implies you do not want any bindings to be used even from the UI. This will not reinstall the UIInputMap(if there was one).Conditionconditionishas one of the following values:
WHEN_IN_FOCUSED_WINDOWWHEN_FOCUSEDorWHEN_ANCESTOR_OF_FOCUSED_COMPONENT.IfconditionisWHEN_IN_FOCUSED_WINDOWandmapis not aComponentInputMapanIllegalArgumentExceptionwill be thrown. Similarly ifconditionis not one of the valuesjustlistedmentionedanIllegalArgumentExceptionwill be thrown. @param condition one of the values listed above @param map theInputMapto use for the given condition @exception IllegalArgumentException ifconditionisWHEN_IN_FOCUSED_WINDOWWHEN_FOCUSEDandWHEN_ANCESTOR_OF_FOCUSED_COMPONENTmapis not an instance ofComponentInputMap; or ifconditionis not one of the legal values specified above @since 1.3
Sets the input verifier for this component. @param inputVerifier the new input verifier @since 1.3 @see InputVerifier @beaninfo bound: true description: The component's input verifier.Class JComponent, void setMaximumSize(Dimension)
Sets the maximum size of this component to a constant value. Subsequent calls toClass JComponent, void setMinimumSize(Dimension)getMaximumSizewill always return this value; the component's UI will not be asked to compute it. Setting the maximum size tonullrestores the default behavior. @param maximumSize aDimensioncontaining the desired maximum allowable size @see #getMaximumSize @beaninfo bound: true description: The maximum size of the component.
Sets the minimum size of this component to a constant value. Subsequent calls toClass JComponent, void setNextFocusableComponent(Component)getMinimumSizewill always return this value; the component's UI will not be asked to compute it. Setting the minimum size tonullrestores the default behavior. @param minimumSize the new minimum size of this component @see #getMinimumSize @beaninfo bound: true description: The minimum size of the component.
Class JComponent, void setOpaque(boolean)SpecifiesOverrides thenextdefaultcomponentFocusTraversalPolicyto getfor thistheJComponent's focusafter this onetraversal cycle byforunconditionally setting the specifiedexampleComponentwhenas thetabnextComponentkey isin thepressed.cycleInvokeand thismethodJComponenttoasoverridethedefaultspecifiedfocus-changeComponent's previousComponentin thesequencecycle. @beaninfoparamexpert:aComponenttruethedescription:ComponentThethatnextshould followcomponentthisJComponentto getin the focusaftertraversalthiscycle @see #getNextFocusableComponent @see java.awt.FocusTraversalPolicy @deprecatedoneAs of 1.4 replaced byFocusTraversalPolicy
If true the component paints every pixel within its bounds. Otherwise the component may not paint some or all of its pixels allowing the underlying pixels to show through.Class JComponent, void setPreferredSize(Dimension)The default value of this property is false for
JComponent. However the default value for this property on most standardJComponentsubclasses (such asJButtonandJTree) is look-and-feel dependent. @param isOpaque true if this component should be opaque @see #isOpaque @beaninfo bound: true expert: true description: The component's opacity
Sets the preferred size ofClass JComponent, void setRequestFocusEnabled(boolean)the receivingthis component. IfpreferredSizeisnullthe UI will be asked for the preferred size. @beaninfo preferred: true bound: true description: The preferred size of the component.
Class JComponent, void setToolTipText(String)SetsProvides a hint as to whetherthe receiving componentor not thiscanJComponentobtain theshould get focus.by callingThis isrequestFocus.onlyThe defaulta hintvalueand it istrue.up to consumers that are requesting focusNote:toSettinghonor this property.toThis is typically honoredfalse willfor mouse operations but notpreventkeyboardtheoperations.focus manager from setting the focus toFor example look and feels could verify thiscomponentpropertyit will prevent the component from gettingis true before requesting focus during athemouse operation. This would often times be used if you did not want a mouse press on aJComponentto steal focuswhenbut did want thefocusJComponentisto be traversablerequestedviaexplicitlythe keyboard.Override isFocusTraversable and return false ifIf you do not want thistheJComponentcomponent should never getfocusable at all use thefocussetFocusablemethod instead. @beaninfoparamexpert:requestFocusEnabledtrueIndicates ifdescription:youWhetherwantthethis JComponentcomponent can obtain theto be focusable orfocusnot @seebyFocuscallingSpecificationrequestFocus@see java.awt.Component#setFocusable
Registers the text to display in a tool tip. The text displays when the cursor lingers over the component.Class JComponent, void setUI(ComponentUI)See How to Use Tool Tips in The Java Tutorial for further documentation. @param text the string to display; if the text is
nullthe tool tip is turned off for this component @see #TOOL_TIP_TEXT_KEY @beaninfo preferred: true description: The text to display in a tool tip.
Sets the look and feel delegate for this component.Class JComponent, void setVerifyInputWhenFocusTarget(boolean)JComponentsubclasses generally override this method to narrow the argument type. For example inJSlider:public void setUI(SliderUI newUI) { super.setUI(newUI); }Additionally
JComponentsubclasses must provide agetUImethod that returns the correct type. For example:public SliderUI getUI() { return (SliderUI)ui; }@param newUI the new UI delegate @see #updateUI @see UIManager#getLookAndFeel @see UIManager#getUI @beaninfo bound: true hidden: true attribute: visualUpdate true description: The component's look and feel delegate.
Class JComponent, void setVisible(boolean)SetSets the value to indicate whether input verifier for the current focus owner will be called before this component requests focus. The default is true. Set to false on components such as a Cancel button or a scrollbar which should activate even if the input in the current focus owner is not "passed" by the input verifier for that component. @paramnewflag value for theverifyInputWhenFocusTargetproperty @see InputVerifier @see #setInputVerifier @see #getInputVerifier @see #getVerifyInputWhenFocusTarget @since 1.3 @beaninfo bound: true description: Whether the Component verifies input before accepting focus.
Makes the component visible or invisible. Overrides Component.setVisible. @param aFlag true to make the component visible; false to make it invisible @beaninfo attribute: visualUpdate true
Class JComponent, void unregisterKeyboardAction(KeyStroke)This method is now obsolete. To unregister an existing binding you can either remove the binding from theClass JComponent, void update(Graphics)ActionMap/InputMapor place a dummy binding theInputMap. Removing the binding from theInputMapallows bindings in parentInputMapsInputMaps to be active whereas putting a dummy binding in theInputMapeffectively disables the binding from ever happening.Unregisters a keyboard action. This will remove the binding from the
ActionMap(if it exists) as well as theInputMapsInputMaps.
CallsClass JComponent, void updateUI()paint. Doesn't clear the background but see(g)ComponentUI.updatewhich is called by()paintComponent. @param g theGraphicscontext in which to paint @see #paint @see #paintComponent @see javax.swing.plaf.ComponentUI
Resets the UI property to a value from the current look and feel.Class JComponent, int WHEN_ANCESTOR_OF_FOCUSED_COMPONENTJComponentsubclasses must override this method like this:public void updateUI() { setUI((SliderUI)UIManager.getUI(this); }@see #setUI @see UIManager#getLookAndFeel @see UIManager#getUI
Constant used for registerKeyboardAction() that means that the command should be invoked when the receiving component is an ancestor of the focused component or is itself the focused component.
Class JComponent, int WHEN_FOCUSEDConstant used for registerKeyboardAction() that means that the command should be invoked when the component has the focus.
Class JComponent, int WHEN_IN_FOCUSED_WINDOWConstant used for registerKeyboardAction() that means that the command should be invoked when the receiving component is in the window that has the focus or is itself the focused component.
Class JComponent, AccessibleContext accessibleContextTheAccessibleContextassociated with thisJComponent.
A container used to create a multiple-document interface or a virtual desktop. You createJInternalFrameobjects and add them to theJDesktopPane.JDesktopPaneextendsJLayeredPaneto manage the potentially overlapping internal frames. It also maintains a reference to an instance ofDesktopManagerthat is set by the UI class for the currentLooklook andFeelfeel (L&F). Note thatJDesktopPanedoes not support borders.This class is normally used as the parent of
JInternalFramesto provide a pluggableDesktopManagerobject to theJInternalFrames. TheinstallUIof the L&F specific implementation is responsible for setting thedesktopManagervariable appropriately. When the parent of aJInternalFrameis aJDesktopPaneit should delegate most of its behavior to thedesktopManager(closing resizing etc).For the keyboard keys used by this component in the standard
Looklook andFeelfeel (L&F) renditions see theJDesktopPanekey assignments. For further documentation and examples see How to Use Internal Frames 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see JInternalFrame @see JInternalFrame.JDesktopIcon @see DesktopManager @version 1.37 0444 12/0603/0001 @author David Kloba
This class implements accessibility support for theJDesktopPaneclass. It provides an implementation of the Java Accessibility API appropriate to desktop pane user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Creates a new JDesktopPane.
Class JDesktopPane, AccessibleContext getAccessibleContext()Gets theClass JDesktopPane, JInternalFrame[] getAllFrames()AccessibleContextassociated with thisJDesktopPane. For desktop panes theAccessibleContexttakes the form of anAccessibleJDesktopPane. A newAccessibleJDesktopPaneinstance is created if necessary. @return anAccessibleJDesktopPanethat serves as theAccessibleContextof thisJDesktopPane
Returns allClass JDesktopPane, JInternalFrame[] getAllFramesInLayer(int)JInternalFramescurrently displayed in the desktop. Returns iconified frames as well as expanded frames. @return an array ofJInternalFrameobjects
Returns allClass JDesktopPane, DesktopManager getDesktopManager()JInternalFramescurrently displayed in the specified layer of the desktop. Returns iconified frames as well expanded frames. @param layer an int specifying the desktop layer @return an array ofJInternalFrameobjects @see JLayeredPane
Returns theClass JDesktopPane, int getDragMode()DesktopMangerthat handles desktop-specific UI actions. @param d theDesktopManagercurrently in use
Class JDesktopPane, JInternalFrame getSelectedFrame()GetGets the current "dragging style" used by the desktop pane. @return eitherLive_DRAG_MODEorOUTLINE_DRAG_MODE@see #setDragMode
Class JDesktopPane, DesktopPaneUI getUI()returnReturns the currently activeJInternalFramein thisJDesktopPaneornullif noJInternalFrameis currently active. @return the currently activeJInternalFrameornull@since 1.3
Returns the L&F object that renders this component. @return the DesktopPaneUI object that renders this component
Class JDesktopPane, String getUIClassID()Returns the name of the L&F class that renders this component. @return the string "DesktopPaneUI" @see JComponent#getUIClassID @see UIDefaults#getUIClass JDesktopPane, String paramString()
Returns a string representation of thisClass JDesktopPane, void setDesktopManager(DesktopManager)JDesktopPane. 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 benull. @return a string representation of thisJDesktopPane.
Sets theClass JDesktopPane, void setDragMode(int)DesktopMangerthat will handle desktop-specific UI actions. @param d theDesktopManagerto use
Class JDesktopPane, void setSelectedFrame(JInternalFrame)SetSets the "dragging style" used by the desktop pane. You may want to change to one mode or another for performance or aesthetic reasons. @param dragMode the style of drag to use for items in the Desktop @see #LIVE_DRAG_MODE @see #OUTLINE_DRAG_MODE @beaninfo bound: true description: Dragging style for internal frame children. enum: LIVE_DRAG_MODE JDesktopPane.LIVE_DRAG_MODE OUTLINE_DRAG_MODE JDesktopPane.OUTLINE_DRAG_MODE
Class JDesktopPane, void setUI(DesktopPaneUI)setSets the currently activeJInternalFramein thisJDesktopPane. @param fThethe internal frame that's currently selected @since 1.3
Sets the L&F object that renders this component. @param ui the DesktopPaneUI L&F object @see UIDefaults#getUI @beaninfo bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.Class JDesktopPane, void updateUI()
Notification from theClass JDesktopPane, int LIVE_DRAG_MODEUIManagerthat the L&F has changed. Replaces the current UI object with the latest version from theUIManager. @see JComponent#updateUI
Class JDesktopPane, int OUTLINE_DRAG_MODEUsed toIndicates thatindicate you wish to seethe entire contents of the item being dragged should appear inside the desktop pane. @see #OUTLINE_DRAG_MODE @see #setDragMode
Used toIndicates thatindicate you wish to see onlyan outline only of the item being dragged should appear inside the desktop pane. @see #LIVE_DRAG_MODE @see #setDragMode
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, constructor JDialog()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 sameprinicipleprinciple 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.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.53 0866 12/0503/0001 @author David Kloba @author James Gosling @author Scott Violet
Creates a non-modal dialog without a title and without a specifiedClass JDialog, constructor JDialog(Dialog)Frameowner. A shared hidden frame will be set as the owner of the dialog.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 JComponent#getDefaultLocale
Creates a non-modal dialog without a title with theClass JDialog, constructor JDialog(Dialog, String)specifedspecifiedDialogas its owner.This constructor sets the component's locale property to the value returned by
JComponent.getDefaultLocale. @param owner the non-nullDialogfrom which the dialog is displayed @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless @see JComponent#getDefaultLocale
Creates a non-modal dialog with the specified title and with the specified owner dialog.Class JDialog, constructor JDialog(Dialog, String, boolean)This constructor sets the component's locale property to the value returned by
JComponent.getDefaultLocale. @param owner the non-nullDialogfrom which the dialog is displayed @param title theStringto display in the dialog's title bar @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless @see JComponent#getDefaultLocale
Creates a modal or non-modal dialog with the specified title and the specified owner frame.Class JDialog, constructor JDialog(Dialog, boolean)This constructor sets the component's locale property to the value returned by
JComponent.getDefaultLocale. @param owner the non-nullDialogfrom which the dialog is displayed @param title theStringto display in the dialog's title bar @param modal true for a modal dialog false for one that allows other windows to be active at the same time @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless @see JComponent#getDefaultLocale
Creates a modal or non-modal dialog without a title and with the specified owner dialog.Class JDialog, constructor JDialog(Frame)This constructor sets the component's locale property to the value returned by
JComponent.getDefaultLocale. @param owner the non-nullDialogfrom which the dialog is displayed @param modal true for a modal dialog false for one that allows other windows to be active at the same time @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless @see JComponent#getDefaultLocale
Creates a non-modal dialog without a title with theClass JDialog, constructor JDialog(Frame, String)specifedspecifiedFrameas its owner. Ifownerisnulla shared hidden frame will be set as the owner of the dialog.This constructor sets the component's locale property to the value returned by
@param owner theJComponent.getDefaultLocale.Framefrom which the dialog is displayed @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless @see JComponent#getDefaultLocale
Creates a non-modal dialog with the specified title and with the specified owner frame. IfClass JDialog, constructor JDialog(Frame, String, boolean)ownerisnulla shared hidden frame will be set as the owner of the dialog.This constructor sets the component's locale property to the value returned by
@param owner theJComponent.getDefaultLocale.Framefrom which the dialog is displayed @param title theStringto display in the dialog's title bar @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless @see JComponent#getDefaultLocale
Creates a modal or non-modal dialog with the specified title and the specified ownerClass JDialog, constructor JDialog(Frame, boolean)Frame. Ifownerisnulla shared hidden frame will be set as the owner of this dialog. All constructors defer to this one.NOTE: Any popup components (
JComboBoxJPopupMenuJMenuBar) created within a modal dialog will be forced to be lightweight.This constructor sets the component's locale property to the value returned by
JComponent.getDefaultLocale. @param owner theFramefrom which the dialog is displayed @param title theStringto display in the dialog's title bar @param modal true for a modal dialog false for one that allows other windows to be active at the same time @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless @see JComponent#getDefaultLocale
Creates a modal or non-modal dialog without a title and with the specified ownerClass JDialog, void addImpl(Component, Object, int)Frame. Ifownerisnulla shared hidden frame will be set as the owner of the dialog.This constructor sets the component's locale property to the value returned by
@param owner theJComponent.getDefaultLocale.Framefrom which the dialog is displayed @param modal true for a modal dialog false for one that allows others windows to be active at the same time @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless @see JComponent#getDefaultLocale
By default children may not be added directly toClass JDialog, void processKeyEvent(KeyEvent)athis component they must be added to itscontentPaneinstead. For example:thisComponent.getContentPane().add(child)An attempt to add to directly to this component will cause an runtime exception to be thrown ifrootPaneCheckingEnabledis true. Subclasses can disable this behavior. @param comp theComponentto be enhanced @param constraints the constraints to be respected @param index the index (an integer) @see #setRootPaneCheckingEnabled @exception Error if called with rootPaneCheckingEnabled true
Processes key events occurring on this componentClass JDialog, void setLayout(LayoutManager)andby dispatching them to any registeredKeyListenerobjects.This method is not called unless key events are enabled for this component. Key events are enabled when one of the following occurs:
- A
KeyListenerobject is registered viaaddKeyListener.- Key events are enabled via
enableEvents.Note that this method is not called by the
event dispatch thread ifappropriatethe componentpasses them on to components inis not the focus owner of if thedialogcomponent is not showing. This method is called whenwhichkey eventshaveare registeredinterestvia theaddKeyListenerorenableEventsmethods but as of release 1.4 the implementation of the AWT event dispatching thread redirectsKeyEventto the focus owner. Please see the Focus Specification for further information.If
the event parameter isnullthe behavior is unspecified and may result intheman exception. @param e the key event @see java.awt.Componentevent.KeyEvent @see java.awt.event.KeyListener @see #addKeyListener @see #enableEvents @see #processKeyEventisShowing @since JDK1.1
By default the layout of this component may not be set the layout of itsClass JDialog, void setLocationRelativeTo(Component)contentPaneshould be set instead. For example:thisComponent.getContentPane().setLayout(newAn attempt to set the layout of this component will cause an runtime exception to be thrown ifBorderLayoutGridLayout(1 2))rootPaneCheckingEnabledis true. Subclasses can disable this behavior. @see #setRootPaneCheckingEnabled @param manager theLayoutManager@exception Error if called with rootPaneChecking true
Sets the location of theClass JDialog, void update(Graphics)dialogwindow relative to the specified component. If the component is not currently showing orcisnullthedialogwindow is centered on the screen. If the bottom of the component is offscreen the window is displayed to the right of the component. @param c the component in relation to which thedialogwindow's location is determined @since 1.4
Callspaint(g). This method was overridden to prevent anunneccessaryunnecessary call to clear the background. @param g theGraphicscontext in which to paint
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.
A futureAsreleaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.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.97 04113 12/0603/0001
This class implements accessibility support for theClass JEditorPane.AccessibleJEditorPane, String getAccessibleDescription()JEditorPaneclass. It provides an implementation of the Java Accessibility API appropriate to editor pane user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Gets the accessibleDescription property of this object. If this property isn't setreturnreturns the content type of thisJEditorPaneinstead (e.g. "plain/text" "html/text"etc). @return the localized description of the object;nullif this object does not have a description @see #setAccessibleName
This class provides support forClass JEditorPane.AccessibleJEditorPaneHTML, Accessible getAccessibleAt(Point)AccessibleHypertextand is used in instances where theEditorKitinstalled in thisJEditorPaneis an instance ofHTMLEditorKit.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.
AAsfutureof 1.4 support for long termreleasestorage ofSwingallwillJavaBeansTMprovide support for baseline forhas been added to theserializedjava.beansformpackage.of SwingPlease seeobjectsjava.beans.XMLEncoder
Returns the Accessible child if one exists contained at the local coordinate Point. @param p The pointClass JEditorPane.AccessibleJEditorPaneHTML, Accessible getAccessibleChild(int)definingrelativethe top-left corner of thetoAccessible given inthe coordinatespacesystem ofthethis object's parent. @return the Accessible if it exists at the specified location;elseotherwise null
Returns theClass JEditorPane.AccessibleJEditorPaneHTML, int getAccessibleChildrenCount()nthspecified Accessible child of the object. The Accessible children of an Accessible object are zero-based so the first child of an Accessible child is at index 0 the second child is at index 1 and so on. @param i zero-based index of child @return thenthAccessible child of the object @see #getAccessibleChildrenCount
Returns the number of accessible childrenin the object. If all of the childrenofthis object implement Accessible than this method should returnthenumber of children of thisobject. @return the number of accessible childreninof the object.
Creates aClass JEditorPane, boolean isManagingFocus()JEditorPanethat has been initialized to the given text. This is a convenience constructor that calls thesetContentTypeandsetTextmethods. @param type mime type of the given text @param text the text to initialize with @exception NullPointerException if thetypeparameter isnull
Class JEditorPane, void processComponentKeyEvent(KeyEvent)Turns offChanges thistabJComponent's focus traversaloncekeys to CTRL+TAB and CTRL+SHIFT+TAB. Also preventsSortingFocusTraversalPolicyfrom considering descendants of this JComponent when computing a focusis gainedtraversal cycle. @returnseetruejava.awt.Component#setFocusTraversalKeysto@seeindicateSortingFocusTraversalPolicythat@deprecatedthe focusAs ofis1.4beingreplacedmanaged;byorComponent.setFocusTraversalKeys(int Set)falseandotherwiseContainer.setFocusCycleRoot(boolean).
Class JEditorPane, void processKeyEvent(KeyEvent)OverriddenProcessestoany keyhandleeventsprocessingthat theofcomponenttab/shiftitselftabrecognizes.IfThis is called after the focus manager and any interestedelistenersidentifieshave been given atabchance to steal away theeditorevent. Thispanemethod isnotcallededitableonlyandif the event hascomponents then thenot yet beenFocusManagerconsumed.is asked to pass focusThis method is called prior to thenext/previouskeyboardcomponentUI logic.@param
eThisthemethod is implemented to do nothing. Subclasses would normally override thiscurrentmethod if they process some key events themselves. If the event is processed it should be consumed.
Class JEditorPane, void setContentType(String)MakeOverridessureprocessKeyEventthat TABto processand Shift-TABeventsget consumed so that awt doesn't attempt focus traversal.@param e the current key event
Sets the type of content that this editor handles. This callsClass JEditorPane, void setPage(URL)getEditorKitForContentTypeand thensetEditorKitif an editor kit can be successfully located. This is mostly convenience method that can be used as an alternative to callingsetEditorKitdirectly.If there is a charset definition specified as a parameter of the content type specification it will be used when loading input streams using the associated
EditorKit. For example if the type is specified astext/html; charset=EUC-JPthe content will be loaded using theEditorKitregistered fortext/htmland the Reader provided to theEditorKitto load unicode into the document will use theEUC-JPcharset for translating to unicode. If the type is not recognized the content will be loaded using theEditorKitregistered for plain texttext/plain. @param type the non-nullmime type for the content editing support @see #getContentType @beaninfo description: the type of content @throw NullPointerException if thetypeparameter isnull
Sets the current URL being displayed. The content type of the pane is set and if the editor kit for the pane is non-nullthen a new default document is created and the URL is read into it. If the URL contains and reference location the location will be scrolled to by calling thescrollToReferencemethod. If the desired URL is not the one currently being displayed thegetStreammethod is called to give subclasses control over the stream provided.This may load either synchronously or asynchronously depending upon the document returned by the
EditorKit. If theDocumentis of typeAbstractDocumentand has a value returned byAbstractDocument.getAsynchronousLoadPrioritythat is greater than or equal to zero the page will be loaded on a separate thread using that priority.If the document is loaded synchronously it will be filled in with the stream prior to being installed into the editor with a call to
setDocumentwhich is bound and will fire a property change event. If anIOExceptionis thrown the partially loaded document will be discarded and neither the document or page property change events will be fired. If the document is successfully loaded and installed a view will be built for it by the UI which will then be scrolled if necessary and then the page property change event will be fired.If the document is loaded asynchronously the document will be installed into the editor immediately using a call to
setDocumentwhich will fire a document property change event then a thread will be created which will begin doing the actual loading. In this case the page property change event will not be fired by the call to this method directly but rather will be fired when the thread doing the loading has finished. It will also be fired on the event-dispatch thread. Since the calling thread can not throw anIOExceptionin the event of failure on the other thread the page property change event will be fired when the other thread is done whether the load was successful or not. @param page the URL of the page @exception IOException for anullor invalid page specification or exception from the stream being read @see #getPage @beaninfo description: the URL used to set content bound: true expert: true
Class JFileChooser, constructor JFileChooser()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 afontfile. @version 1.68920212/0903/01 @author Jeff Dinkins
Constructs a JFileChooser pointing to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows and the user's home directory on Unix.
Class JFileChooser, constructor JFileChooser(File)Constructs aClass JFileChooser, constructor JFileChooser(String)JFileChooserusing the givenFileas the path. Passing in anullfile causes the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows and the user's home directory on Unix. @param currentDirectory aFileobject specifying the path to a file or directory
Constructs aClass JFileChooser, void addActionListener(ActionListener)JFileChooserusing the given path. Passing in anullstring causes the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows and the user's home directory on Unix. @param currentDirectoryPath aStringgiving the path to a file or directory
Adds anClass JFileChooser, void addChoosableFileFilter(FileFilter)ActionListenerto thebuttonfile chooser. @param l the listener to be added @see #approveSelection @see #cancelSelection
Adds a filter to the list of user choosable file filters. @param filter theClass JFileChooser, void approveSelection()FileFilterto add to the choosable file filter list @beaninfo preferred: true bound: true description: Adds a filter to the list of user choosable file filters. @see #getChoosableFileFilters @see #removeChoosableFileFilter @see #resetChoosableFileFilterresetChoosableFileFilters
Called by the UI when the user hits the Approve button (labeled "Open" or "Save" by default). This can also be called by the programmer. This method causes an action event to fire with the command string equal to APPROVE_SELECTION. @see #APPROVE_SELECTION
Class JFileChooser, void cancelSelection()Called by the UI when the user chooses the Cancel button. This can also be called by the programmer. This method causes an action event to fire with the command string equal to CANCEL_SELECTION. @see #CANCEL_SELECTION
Class JFileChooser, void fireActionPerformed(String)Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using theClass JFileChooser, FileFilter[] getChoosableFileFilters()parameterscommandpassed into the fire methodparameter. @see EventListenerList
Gets the list of user choosable file filters. @return aClass JFileChooser, boolean getControlButtonsAreShown()FileFilterarray containing all the choosable file filters @see #addChoosableFileFilter @see #removeChoosableFileFilter @see #resetChoosableFileFilterresetChoosableFileFilters
ReturnsClass JFileChooser, void removeActionListener(ActionListener)a boolean indicating whethertheaccept and cancel buttons arevalueshownofinthefilecontrolButtonsAreShownchooserproperty. @returntrue iftheaccept &valuecancelofbuttons are shown;theotherwisecontrolButtonsAreShownfalseproperty @see #setControlButtonsAreShown @since 1.3
Removes anClass JFileChooser, boolean removeChoosableFileFilter(FileFilter)ActionListenerfrom thebuttonfile chooser. @param l the listener to be removed @see #addActionListener
Removes a filter from the list of user choosable file filters. Returns true if the file filter was removed. @Class JFileChooser, void setAcceptAllFileFilterUsed(boolean)see #addChoosableFileFilter @see #getChoosableFileFilters @see #resetChoosableFileFilterresetChoosableFileFilters
DeterminesClass JFileChooser, void setControlButtonsAreShown(boolean)ifwhether theAcceptAll FileFilteris used as an available choice in the choosable filter list. If false theAcceptAllfile filter is removed from the list of available file filters. If true theAcceptAllfile filter will become the the actively used file filter. @beaninfo preferred: true bound: true description: Sets whether the AcceptAll FileFilter is used as an available choice in the choosable filter list. @see #isAcceptAllFileFilterUsed @see #getAcceptAllFileFilter @see #setFileFilter @since 1.3
Sets the property that indicates whether the approve and cancel buttons are shown in the file chooser. This property isClass JFileChooser, void setCurrentDirectory(File)trueby default. Look and feels that always show these buttons will ignore the value of this property. This method fires a property-changed event using the string value ofCONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTYas the name of the property. @param bfalseif control buttons should not be shown; otherwisetrue@beaninfo preferred: true bound: true description: Sets whether the approve & cancel buttons are shown. @see #getControlButtonsAreShown @see #CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY @since 1.3
Sets the current directory. Passing inClass JFileChooser, int showDialog(Component, String)nullsets the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows and the user's home directory on Unix. If the file passed in ascurrentDirectoryis not a directory the parent of the file will be used as the currentDirectory. If the parent is not traversable then it will walk up the parent tree until it finds a traversable directory or hits the root of the file system. @beaninfo preferred: true bound: true description: The directory that the JFileChooser is showing files of. @param dir the current directory to point to @see #getCurrentDirectory
Pops a custom file chooser dialog with a custom approve button. For example the following code pops up a file chooser with a "Run Application" button (instead of the normal "Save" or "Open" button):Class JFileChooser, int showOpenDialog(Component)filechooser.showDialog(parentFrame "Run Application");Alternatively the following code does the same thing:JFileChooser chooser = new JFileChooser(null); chooser.setApproveButtonText("Run Application"); chooser.showDialog(parentFrame null);<--PENDING(jeff) - the following method should be added to the api: showDialog(Component parent);--> <--PENDING(kwalrath) - should specify modality and what "depends" means.-->The
parentargument determines two things: the frame on which the open dialog depends and the component whose position the look and feel should consider when placing the dialog. If the parent is aFrameobject (such as aJFrame) then the dialog depends on the frame and the look and feel positions the dialog relative to the frame (for example centered over the frame). If the parent is a component then the dialog depends on the frame containing the component and is positioned relative to the component (for example centered over the component). If the parent isnullthen the dialog depends on no visible window and it's placed in a look-and-feel-dependent position such as the center of the screen. @param parent the parent component of the dialog; can benull@param approveButtonText the text of theApproveButton@return the return state of the file chooser on popdown:@exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless
- JFileChooser.CANCEL_OPTION
- JFileChooser.APPROVE_OPTION
- JFileCHooser.ERROR_OPTION if an error occurs or the dialog is dismissed
Pops up an "Open File" file chooser dialog. Note that the text that appears in the approve button is determined by the L&F. @param parent the parent component of the dialog can beClass JFileChooser, int showSaveDialog(Component)null; seeshowDialogfor details @return the return state of the file chooser on popdown:@exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless @see #showDialog
- JFileChooser.CANCEL_OPTION
- JFileChooser.APPROVE_OPTION
- JFileCHooser.ERROR_OPTION if an error occurs or the dialog is dismissed
Pops up a "Save File" file chooser dialog. Note that the text that appears in the approve button is determined by the L&F. @param parent the parent component of the dialog can beClass JFileChooser, void updateUI()null; seeshowDialogfor details @return the return state of the file chooser on popdown:@exception HeadlessException if GraphicsEnvironment.isHeadless() returns true. @see java.awt.GraphicsEnvironment#isHeadless @see #showDialog
- JFileChooser.CANCEL_OPTION
- JFileChooser.APPROVE_OPTION
- JFileCHooser.ERROR_OPTION if an error occurs or the dialog is dismissed
NotificationResetsfromtheUIFactoryUI property tothata value from theL&Fcurrent lookhas changedand feel. @see JComponent#updateUI
An extended version ofClass JFrame, constructor JFrame()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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.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.79 0890 12/0503/0001 @author Jeff Dinkins @author Georges Saab @author David Kloba
Constructs a new frame that is initially invisible.Class JFrame, constructor JFrame(GraphicsConfiguration)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
Creates aClass JFrame, constructor JFrame(String)Framein the specifiedGraphicsConfigurationof a screen device and a blank title.This constructor sets the component's locale property to the value returned by
JComponent.getDefaultLocale. @param gc theGraphicsConfigurationthat is used to construct the newFrame; ifgcisnullthe system defaultGraphicsConfigurationis assumed @exception IllegalArgumentException ifgcis 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
Creates a new initially invisibleClass JFrame, constructor JFrame(String, GraphicsConfiguration)Framewith 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
Creates aClass JFrame, void processKeyEvent(KeyEvent)JFramewith the specified title and the specifiedGraphicsConfigurationof 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. Anullvalue is treated as an empty string "". @param gc theGraphicsConfigurationthat is used to construct the newJFramewith; ifgcisnullthe system defaultGraphicsConfigurationis assumed @exception IllegalArgumentException ifgcis 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
Processes key events occurring on this componentClass JFrame, void setDefaultCloseOperation(int)andby dispatching them to any registeredKeyListenerobjects.This method is not called unless key events are enabled for this component. Key events are enabled when one of the following occurs:
- A
KeyListenerobject is registered viaaddKeyListener.- Key events are enabled via
enableEvents.Note that this method is not called by the
event dispatch thread ifappropriatethe componentpasses them on to components inis not the focus owner of if theframecomponent is not showing. This method is called whenwhichkey eventshaveare registeredinterestvia theaddKeyListenerorenableEventsmethods but as of release 1.4 the implementation of the AWT event dispatching thread redirectsKeyEventto the focus owner. Please see the Focus Specification for further information.If
the event parameter isnullthe behavior is unspecified and may result intheman exception. @param e the key event @see java.awt.Componentevent.KeyEvent @see java.awt.event.KeyListener @see #addKeyListener @see #enableEvents @see #processKeyEventisShowing @since JDK1.1
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 setLayout(LayoutManager)
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 @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_CLOSEJFrameWindowConstants.EXIT_ON_CLOSE description: The frame's default close operation.
By default the layout of this component may not be set the layout of itscontentPaneshould be set instead. For example:An attempt to set the layout of this component will cause an runtime exception to be thrown. Subclasses can disable this behavior. @param manager thethiComponentthisComponent.getContentPane().setLayout(newBorderLayoutGridLayout(1 2))LayoutManager@exception Error if called withrootPaneCheckingtrue @see #setRootPaneCheckingEnabled
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.Generally you add
JInternalFrames to aJDesktopPane. The UI delegates the look-and-feel-specific actions to theDesktopManagerobject maintained by theJDesktopPane.The
JInternalFramecontentPanecontent pane is where you add child components. So to create aJInternalFramethat has a number of buttons arranged withathe content pane's defaultBorderLayoutobject you might do something like this:JComponent c = (JComponent)TheframeinternalFrame.getContentPane(); c.setLayout(new BorderLayout()); c.add(new JButton() BorderLayout.NORTH); c.add(new JButton() BorderLayout.CENTER);contentPanecontent pane is actually managed by an instance ofJRootPanewhich also manages alayoutPanelayoutglassPanepane glass pane and optionalmenuBarmenu 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
Looklook andFeel (L&F)feel renditions see theJInternalFramekey 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see InternalFrameEvent @see JDesktopPane @see DesktopManager @see JInternalFrame.JDesktopIcon @see JRootPane @version 1.116 02135 12/0903/01 @author David Kloba @author Rich Schiavi @beaninfo attribute: isContainer true attribute: containerDelegate getContentPane description: A frame container which is contained within another window.
This class implements accessibility support for theClass JInternalFrame.AccessibleJInternalFrame, String getAccessibleName()JInternalFrameclass. It provides an implementation of the Java Accessibility API appropriate to internal frame user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Get the accessible name of this object. @return the localized name of the object -- can be null if this object does not have a name @see #setAccessibleName
Class JInternalFrame.AccessibleJInternalFrame, AccessibleValue getAccessibleValue()Class JInternalFrame.AccessibleJInternalFrame, Number getCurrentAccessibleValue()GetGets the AccessibleValue associated with this object. In the implementation of the Java Accessibility API for this classreturnreturns this object which is responsible for implementing theAccessibleValueinterface on behalf of itself. @return this object
Get the value of this object as a Number. @return value of the object -- can be null if this object does not have a value
Class JInternalFrame.AccessibleJInternalFrame, Number getMaximumAccessibleValue()Get the maximum value of this object as a Number. @return Maximum value of the object; null if this object does not have a maximum value
Class JInternalFrame.AccessibleJInternalFrame, Number getMinimumAccessibleValue()Get the minimum value of this object as a Number. @return Minimum value of the object; null if this object does not have a minimum value
Class JInternalFrame.AccessibleJInternalFrame, boolean setCurrentAccessibleValue(Number)Set the value of this object as a Number. @returnTruetrueif the value was set.
This component represents an iconified version of aJInternalFrame. This API should NOT BE USED by Swing applications as it will go away in future versions of Swing as its functionality is moved intoJInternalFrame. This class is public only so that UI objects can display a desktop icon. If an application wants to display a desktop icon it should create aJInternalFrameinstance and iconify it.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @author David Kloba
This class implements accessibility support for theClass JInternalFrame.JDesktopIcon.AccessibleJDesktopIcon, AccessibleRole getAccessibleRole()JInternalFrame.JDesktopIconclass. It provides an implementation of the Java Accessibility API appropriate to desktop icon user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Class JInternalFrame.JDesktopIcon.AccessibleJDesktopIcon, AccessibleValue getAccessibleValue()GetGets the role of this object. @return an instance of AccessibleRole describing the role of the object @see AccessibleRole
Class JInternalFrame.JDesktopIcon.AccessibleJDesktopIcon, Number getCurrentAccessibleValue()GetGets the AccessibleValue associated with this object. In the implementation of the Java Accessibility API for this classreturnreturns this object which is responsible for implementing theAccessibleValueinterface on behalf of itself. @return this object
Class JInternalFrame.JDesktopIcon.AccessibleJDesktopIcon, Number getMaximumAccessibleValue()GetGets the value of this object as aNumber. @return value of the object -- can benullif this object does not have a value
Class JInternalFrame.JDesktopIcon.AccessibleJDesktopIcon, Number getMinimumAccessibleValue()GetGets the maximum value of this object as aNumber. @returnMaximummaximum value of the object;nullif this object does not have a maximum value
Class JInternalFrame.JDesktopIcon.AccessibleJDesktopIcon, boolean setCurrentAccessibleValue(Number)GetGets the minimum value of this object as aNumber. @returnMinimumminimum value of the object;nullif this object does not have a minimum value
SetSets the value of this object as aNumber. @returnTruetrueif the value was set.
Class JInternalFrame.JDesktopIcon, JDesktopPane getDesktopPane()CreateCreates an icon for an internal frame. @param f theJInternalFramefor which the icon is created
Class JInternalFrame.JDesktopIcon, JInternalFrame getInternalFrame()ConvienceConvenience method to ask the icon for theDesktopobject it belongs to. @return theJDesktopPanethat contains this icon's internal frame ornullif none found
Returns theClass JInternalFrame.JDesktopIcon, DesktopIconUI getUI()JInternalFramethat thisDesktopIconis associated with. @return theJInternalFramewith which this icon is associatedwith
Returns theClass JInternalFrame.JDesktopIcon, String getUIClassID()L&Flook-and-feel object that renders this component. @return theDesktopIconUIobject that renders this component
Returns the name of theClass JInternalFrame.JDesktopIcon, void setInternalFrame(JInternalFrame)L&Flook-and-feel class that renders this component. @return the string "DesktopIconUI" @see JComponent#getUIClassID @see UIDefaults#getUI
Sets theClass JInternalFrame.JDesktopIcon, void setUI(DesktopIconUI)JInternalFramethatwith which thisDesktopIconis associatedwith. @param f theJInternalFramewith which this icon is associatedwith
Sets theClass JInternalFrame.JDesktopIcon, void updateUI()L&Flook-and-feel object that renders this component. @param ui theDesktopIconUIL&Flook-and-feel object @see UIDefaults#getUI
Notification from theUIManagerthat theL&Flook and feel has changed. Replaces the current UI object with the latest version from theUIManager. @see JComponent#updateUI
Creates a non-resizable non-closable non-maximizable non-iconifiableClass JInternalFrame, constructor JInternalFrame(String, boolean)JInternalFramewith the specified title. Note that passing in anulltitleresults in unspecified behavior and possibly an exception. @param title the non-nullStringto display in the title bar
Creates a non-closable non-maximizable non-iconifiableClass JInternalFrame, constructor JInternalFrame(String, boolean, boolean)JInternalFramewith the specified title andwithresizabilityspecified. @param title theStringto display in the title bar @param resizable iftruethe internal frame can be resized
Creates a non-maximizable non-iconifiableClass JInternalFrame, constructor JInternalFrame(String, boolean, boolean, boolean)JInternalFramewith the specified titleand withresizability and closabilityspecified. @param title theStringto display in the title bar @param resizable iftruethe internal frame can be resized @param closable iftruethe internal frame can be closed
Creates a non-iconifiableClass JInternalFrame, constructor JInternalFrame(String, boolean, boolean, boolean, boolean)JInternalFramewith the specified titleand withresizability closability and maximizabilityspecified. @param title theStringto display in the title bar @param resizable iftruethe internal frame can be resized @param closable iftruethe internal frame can be closed @param maximizable iftruethe internal frame can be maximized
Creates aClass JInternalFrame, void addImpl(Component, Object, int)JInternalFramewith the specified titleand withresizability closability maximizability and iconifiabilityspecified. AllconstructorsJInternalFramedefer toconstructors use this one. @param title theStringto display in the title bar @param resizable iftruethe internal frame can be resized @param closable iftruethe internal frame can be closed @param maximizable iftruethe internal frame can be maximized @param iconifiable iftruethe internal frame can be iconified
Class JInternalFrame, void addInternalFrameListener(InternalFrameListener)ByEnsures that by default childrenmay notcannot be added directly toathis component.theyInstead children must be added to itscontentPanecontentinsteadpane. For example:thisComponent.getContentPane().add(child)An attempt to add to directly to this component will causeana runtime exception to be thrown. Subclasses can disable this behavior. @param comp theComponentto be added @param constraints the object containing the constraints if any @param index the index @see #setRootPaneCheckingEnabled @exception Error if called withisRootPaneCheckingtrue
Adds the specifiedClass JInternalFrame, void dispose()internal framelistener to receive internal frame events from this internal frame. @param l the internal frame listener
Class JInternalFrame, AccessibleContext getAccessibleContext()DisposesMakesofthis internal frame invisible unselected and closed. If the frame is not already closedathis method fires anINTERNAL_FRAME_CLOSEDevent. The results of invoking this method are similar tosetClosed(true)butdisposealways succeeds in closing the internal frame-closedand does not fire anINTERNAL_FRAME_CLOSINGevent.is@seepostedjavax.swing.event.InternalFrameEvent#INTERNAL_FRAME_CLOSED @see #setVisible @see #setSelected @see #setClosed
Gets theClass JInternalFrame, int getDefaultCloseOperation()AccessibleContextassociated with thisJInternalFrame. For internal frames theAccessibleContexttakes the form of anAccessibleJInternalFrameobject. A newAccessibleJInternalFrameinstance is created if necessary. @return anAccessibleJInternalFramethat serves as theAccessibleContextof thisJInternalFrame@see AccessibleJInternalFrame
Returns the default operationClass JInternalFrame, JDesktopIcon getDesktopIcon()whichthat occurs when the user initiates a "close" on thiswindowinternal frame. @return the operation that will occur when the user closes the internal frame @see #setDefaultCloseOperation
Returns theClass JInternalFrame, JDesktopPane getDesktopPane()JDesktopIconused when thisJInternalFrameis iconified. @return theJDesktopIcondisplayed on the desktop @see #setDesktopIcon
Convenience method thatClass JInternalFrame, Component getFocusOwner()searchssearches theanscestorancestorheirarchyhierarchy for aJDesktopinstance. IfJInternalFramefinds none thedesktopIcontree is searched. @return theJDesktopPanethis internal frame belongs to ornullif none is found
If thisClass JInternalFrame, Icon getFrameIcon()JInternalFrameis activereturnreturns the childwhichthat has focus. Otherwisereturnreturnsnull. @return the component with focus or. At present this method works only for JComponent childrennullif no children have focusassigned to them.@since 1.3
Returns the image displayed in the title bar ofClass JInternalFrame, Component getGlassPane()thethis internal frame (usually in the top-left corner). @return theIcondisplayed in the title bar @see #setFrameIcon
Returns theClass JInternalFrame, JMenuBar getJMenuBar()glassPaneglassobjectpane for this internal frame. @return theglassPaneglassobjectpane @see RootPaneContainer#setGlassPane
Returns the currentClass JInternalFrame, int getLayer()JMenuBarfor thisJInternalFrameornullif no menu bar has been set. @return theJMenuBarused by this internal frame @see #setJMenuBar
Convenience method for getting the layer attribute of this component. @return an Integer object specifying this frame's desktop layer @see JLayeredPane
Class JInternalFrame, JLayeredPane getLayeredPane()Returns theClass JInternalFrame, JMenuBar getMenuBar()layeredPanelayeredobjectpane for this internal frame. @returntheaobject @see RootPaneContainer#setLayeredPane @see RootPaneContainer#getLayeredPanelayeredPaneJLayeredPane
Returns the currentClass JInternalFrame, Rectangle getNormalBounds()JMenuBarfor thisJInternalFrameornullif no menu bar has been set. @return the currentmenubarmenu bar ornullif none has been set @deprecated As of Swing version 1.0.3 replaced bygetJMenuBar().
If theClass JInternalFrame, JRootPane getRootPane()JInternalFrameis not in maximized statereturnreturnsgetBounds(); otherwisereturnreturns the bounds that theJInternalFramewould be restored to. @return aRectanglecontaining the bounds of this frame when in the normal state @since 1.3
Returns theClass JInternalFrame, String getTitle()rootPaneobject for this internal frame. @return therootPaneproperty @see RootPaneContainer#getRootPane
Returns the title of theClass JInternalFrame, InternalFrameUI getUI()JInternalFrame. @return aStringcontainingthethis internal frame's title @see #setTitle
Returns theClass JInternalFrame, String getUIClassID()L&Flook-and-feel object that renders this component. @return theInternalFrameUIobject that renders this component
Returns the name of theClass JInternalFrame, String getWarningString()L&Flook-and-feel classwhichthat renders this component. @return the string "InternalFrameUI" @see JComponent#getUIClassID @see UIDefaults#getUI @beaninfo description: UIClassID
Gets the warning string that is displayed with thisClass JInternalFrame, boolean isClosable()windowinternal frame. Since an internal frame is always secure (since it's fully contained within a windowwhichthat might need a warning string) this method always returnsnull. @returnnull@see java.awt.Window#getWarningString
Returns whether thisClass JInternalFrame, boolean isClosed()JInternalFramecan be closed by some user action. @returntrueifthethis internal frame can be closed
Returns whether thisClass JInternalFrame, boolean isIcon()JInternalFrameis currently closed. @returntrueifthethis internal frame is closedfalseotherwise
Returns whether theClass JInternalFrame, boolean isIconifiable()JInternalFrameis currently iconified. @returntrueifthethis internal frame is iconified
Class JInternalFrame, boolean isMaximizable()ReturnsGetswhethertheJInternalFrameiconablecan bepropertyiconifiedwhich bysomedefaultuserisactionfalse. @returntruethe valueifof theframeiconablecanproperty.be@seeiconified#setIconifiable
Class JInternalFrame, boolean isMaximum()ReturnsGetswhethertheJInternalFrame canvaluebeofmaximized by sometheusermaximizableactionproperty. @returntruethe valueifof theframemaximizablecanpropertybe@seemaximized#setMaximizable
Returns whether theClass JInternalFrame, boolean isResizable()JInternalFrameis currently maximized. @returntrueifthethis internal frame is maximizedfalseotherwise
Returns whether theClass JInternalFrame, boolean isRootPaneCheckingEnabled()JInternalFramecan be resized by some user action. @returntrueifthethis internal frame can be resizedfalseotherwise
Returns whether calls toClass JInternalFrame, boolean isSelected()addandsetLayoutcause an exception to be thrown. @returntrueifaddandsetLayoutare checked @see #addImpl @see #setLayout @see #setRootPaneCheckingEnabled
Returns whether theClass JInternalFrame, void moveToBack()JInternalFrameis the currently "selected" or active frame. @returntrueifthethis internal frame is currently selected (active) @see #setSelected
Convenience method that moves this component to position -1 if its parent is a JLayeredPane.
Class JInternalFrame, void moveToFront()Convenience method that moves this component to position 0 if its parent is a JLayeredPane.
Class JInternalFrame, void pack()Causes subcomponents of this JInternalFrame to be laid out at their preferred size. @see java.awt.Window#pack
Class JInternalFrame, String paramString()Returns a string representation of thisClass JInternalFrame, void reshape(int, int, int, int)JInternalFrame. 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 benull. @return a string representation of thisJInternalFrame.
Moves and resizes this component. Unlike other components this implementation also forces re-layout so that frame decorations such as the title bar are always redisplayed. @param x anClass JInternalFrame, void restoreSubcomponentFocus()intinteger giving the component's new horizontal position measured in pixels from the left of its container @param y anintinteger giving the component's new vertical position measured in pixels from the bottom of its container @param width anintinteger giving the component's new width in pixels @param height anintinteger giving the component's new height in pixels
Class JInternalFrame, void setClosable(boolean)This method directsRequests the internal frame to restore focus to the last subcomponent that had focus. This is used by the UI when the user selectedthethis internal framee.g.-- for example by clicking on the title bar. @since 1.3
SetsClass JInternalFrame, void setClosed(boolean)thatwhether thisJInternalFramecan be closed by some user action. @param b a boolean value wheretruemeansthethis internal frame can be closed @beaninfo preferred: true bound: true description: Indicates whether this internal frame can be closed.
Class JInternalFrame, void setContentPane(Container)CallingCloses this internal frame if the argument istrue. Do not invoke this method with avaluefalseargument; the result of invokingis unspecified.truesetClosed(false)If the internal frame is already closed this method does nothing and returns immediately. Otherwise this method begins by firing an
INTERNAL_FRAME_CLOSINGevent. Then this method sets theclosedproperty toclosetrueunless a listener vetoes the property change. This method finishes by making the internal frame invisible and unselected and then firing anINTERNAL_FRAME_CLOSEDevent.@param
bNote: To reuse an internal frame that has been closed you must add it to abooleancontainerwhere(eventrueif you never removed it from itsmeansprevious"closecontainer). Typically this container will be theJDesktopPanethat previously contained the internal frame". @param b must betrue@exception PropertyVetoException when the attempt to set the property is vetoed by theJInternalFrame@see #isClosed() @see #setDefaultCloseOperation @see #dispose @see javax.swing.event.InternalFrameEvent#INTERNAL_FRAME_CLOSING @beaninfo bound: true constrained: true description: Indicatesthatwhetherthethis internal frame has been closed.
Sets thisClass JInternalFrame, void setDefaultCloseOperation(int)JInternalFrame'scontentcontentPanepaneproperty. @param c thecontentPanecontentobjectpane for this internal frame @exception java.awt.IllegalComponentStateException (a runtime exception) if the content pane parameter isnull@see RootPaneContainer#getContentPane @beaninfo bound: true hidden: true description: The client area of the internal frame where child components are normally inserted.
Sets the operationClass JInternalFrame, void setDesktopIcon(JDesktopIcon)whichthat will happen by default when the user initiates a "close" on thiswindowinternal frame. The possible choices are:
DO_NOTHING_ON_CLOSE-do not- Do
do anythingnothing.- requireThis requires the program to handle the operation in thewindowClosingmethod of a registeredInternalFrameListenerobject.HIDE_ON_CLOSE- automatically hide- Automatically make the
windowinternalafterframeinvokinginvisible.DISPOSE_ON_CLOSEany registered- Automatically
InternalFrameListenerdispose of the internal frame.The default value
objectsisDISPOSE_ON_CLOSE.- automatically hide and disposeBefore performing the specified close operation thewindow after invoking anyinternal frame fires anregisteredINTERNAL_FRAME_CLOSINGInternalFrameListenerevent.objects@paramThe value is set tooperation one of the following constants definedDISPOSEinjavax.swing.WindowConstants(an interface implemented byJInternalFrame):DO_NOTHING_ON_CLOSEbyHIDE_ON_CLOSEdefault.orDISPOSE_ON_CLOSE@see #addInternalFrameListener @see #getDefaultCloseOperation @see #setVisible @see #dispose @see InternalFrameEvent#INTERNAL_FRAME_CLOSING
Sets theClass JInternalFrame, void setFrameIcon(Icon)JDesktopIconassociated with thisJInternalFrame. @param d theJDesktopIconto display on the desktop @see #getDesktopIcon @beaninfo bound: true description: The icon shown when this internal frame is minimized.
Sets an image to be displayed in the titlebar ofClass JInternalFrame, void setGlassPane(Component)thethis internal frame (usually in the top-left corner). This image is not thedesktopIconobject which is the image displayed in theJDesktopwhenthethis internal frame is iconified. Passingnullto this function is valid but theL&Flook and feel can choose the appropriate behavior for that situation such as displaying no icon or a default icon for theL&Flook and feel. @param icon theIconto display in the title bar @see #getFrameIcon @beaninfo bound: true description: The icon shown in the top-left corner ofthethis internal frame.
Sets thisClass JInternalFrame, void setIcon(boolean)JInternalFrame'sglassPaneproperty. @paramglassPaneglass theglassPaneglassobjectpane for this internal frame @see RootPaneContainer#getGlassPane @beaninfo bound: true hidden: true description: A transparent pane used for menu rendering.
Class JInternalFrame, void setIconifiable(boolean)Iconizes andIconifies or de-iconizesiconifies this internal frame if the look and feel supports iconification. If the internal frame's state changes to iconified this method fires anINTERNAL_FRAME_ICONIFIEDevent. If the state changes to de-iconified anINTERNAL_FRAME_DEICONIFIEDevent is fired. @param b a boolean wheretruemeans to iconifythethis internal frame andfalsemeans to de-iconify it @exception PropertyVetoException when the attempt to set the property is vetoed by theJInternalFrame@see InternalFrameEvent#INTERNAL_FRAME_ICONIFIED @see InternalFrameEvent#INTERNAL_FRAME_DEICONIFIED @beaninfo bound: true constrained: true description: The image displayed when this internal frame is minimized.
SetsClass JInternalFrame, void setJMenuBar(JMenuBar)thattheJInternalFrameiconablecanproperty which must betruefor the user to bemadeable to make theJInternalFramean icon.by someSome lookuserand feels might not implement iconification; they will ignore thisactionproperty. @param b a boolean wheretruemeansthethis internal frame can be iconified @beaninfo preferred: true bound: true description: Determines whether this internal frame can be iconified.
Sets theClass JInternalFrame, void setLayer(Integer)property for thisJMenuBarmenuBarJInternalFrame. @param m theJMenuBarto use in this internal frame @see #getJMenuBar @beaninfo bound: true preferred: true description: Themenubarmenu bar for accessing pulldown menus from this internal frame.
Convenience method for setting the layer attribute of this component. @param layer an Integer object specifying this frame's desktop layer @see JLayeredPane @beaninfo expert: true description: Specifies what desktop layer is used.
Class JInternalFrame, void setLayer(int)Convenience method for setting the layer attribute of this component. The methodClass JInternalFrame, void setLayeredPane(JLayeredPane)setLayer(Integer)should be used for layer values predefined inJLayeredPane. When usingsetLayer(int)care must be taken not to accidentally clash with those values. @param layer anintinteger specifying this internal frame's desktop layer @since 1.3 @see #setLayer(Integer) @see JLayeredPane @beaninfo expert: true description: Specifies what desktop layer is used.
Sets thisClass JInternalFrame, void setLayout(LayoutManager)JInternalFrame'slayeredPaneproperty. @param layered thelayeredPaneJLayeredPaneobjectfor this internal frame @exception java.awt.IllegalComponentStateException (a runtime exception) if the layered pane parameter isnull@see RootPaneContainer#setLayeredPane @beaninfo hidden: true bound: true description: The pane which holds the various desktop layers.
Class JInternalFrame, void setMaximizable(boolean)ByEnsures that by default the layout of this componentmay notcannot be set. Instead the layout of itscontentPanecontent pane should be setinstead. For example:thisComponent.getContentPane().setLayout(newAn attempt to set the layout of this component will cause an runtime exception to be thrown. Subclasses can disable this behavior. @param manager theBorderLayoutGridLayout(1 2))LayoutManager@see #setRootPaneCheckingEnabled @exception Error if called withisRootPaneCheckingtrue
SetsClass JInternalFrame, void setMaximum(boolean)thatthemaximizableproperty which determines whether theJInternalFramecan be maximized by some user action. Some look and feels might not support maximizing internal frames; they will ignore this property. @param batrueboolean where true means theto specify that this internal framecanshould bemaximizedmaximizable;falseto specify that it should not be @beaninfo bound: true preferred: true description: Determines whether this internal frame can be maximized.
Maximizes and restoresClass JInternalFrame, void setMenuBar(JMenuBar)thethis internal frame. A maximized frame is resized to fully fit theJDesktopPanearea associated with theJInternalFrame. A restored frame's size is set to theJInternalFrame's actual size. @param b a boolean wheretruemaximizesthethis internal frame andfalserestores it @exception PropertyVetoException when the attempt to set the property is vetoed by theJInternalFrame@beaninfo bound: true constrained: true description: Indicates whetherthethis internal frame is maximized.
Sets theClass JInternalFrame, void setNormalBounds(Rectangle)property for thisJMenuBarmenuBarJInternalFrame. @param m theJMenuBarto use in this internal frame @see #getJMenuBar @deprecated As of Swing version 1.0.3 replaced bysetJMenuBar(JMenuBar m).
Sets the normal bounds for this internal frame the bounds thatClass JInternalFrame, void setResizable(boolean)thethis internal frame would be restored to from its maximized state. This method is intended for use only by desktop managers. @param r the bounds thatthethis internal frame should be restored to @since 1.3
SetsClass JInternalFrame, void setRootPane(JRootPane)thatwhether theJInternalFramecan be resized by some user action. @param b a boolean wheretruemeansthethis internal frame can be resized @beaninfo preferred: true bound: true description: Determines whetherthethis internal frame can be resized by the user.
Sets theClass JInternalFrame, void setRootPaneCheckingEnabled(boolean)rootPaneproperty for thisJInternalFrame. This method is called by the constructor. @param root the newobject @beaninfo bound: true hidden: true description: TherootPaneJRootPanerootPaneroot pane used by this internal frame.
Determines whether calls toClass JInternalFrame, void setSelected(boolean)addandsetLayoutcause an exception to be thrown. @param enabled a boolean valuetrueif checking is to be enabled which cause the exceptions to be thrown @see #addImpl @see #setLayout @see #isRootPaneCheckingEnabled
SelectsClass JInternalFrame, void setUI(InternalFrameUI)andor deselects theJInternalFrameinternal frame if it's showing. AJInternalFramenormally draws its title bar differently if it is the selected frame which indicates to the user that thisinternalFrameinternal frame has the focus. When this method changes the state of the internal frame from deselected to selected it fires anInternalFrameEvent.INTERNAL_FRAME_ACTIVATEDevent. If the change is from selected to deselected anInternalFrameEvent.INTERNAL_FRAME_DEACTIVATEDevent is fired. @param selected a boolean wheretruemeansthethis internal frameisshould become selected (currently active) andfalsemeans itisshould becomenotdeselected @exception PropertyVetoException when the attempt to set the property is vetoed by thereceiver.JInternalFrame@see #isShowing @see InternalFrameEvent#INTERNAL_FRAME_ACTIVATED @see InternalFrameEvent#INTERNAL_FRAME_DEACTIVATED @beaninfo constrained: true bound: true description: Indicates whether this internal frame is currently the active frame.
Sets the UI delegate for thisClass JInternalFrame, void show()JInternalFrame. @param ui the UI delegate @beaninfoexpertbound: true hidden: true attribute: visualUpdate true description: TheInternalFrameUI implementationUI object thatdefinesimplements thelabels look andComponent'sfeelLookAndFeel.
Class JInternalFrame, void toBack()Shows thisIf the internal frameandis not visible bringsitthe internal frame to the front makes it visible and attempts to select it.If this window is notThe first time the internal frameyetis made visible this method also fires anshowINTERNAL_FRAME_OPENEDmakesevent.itThisvisible.methodIfdoesthisnothing if the internalwindowframe is already visible.thenInvoking this methodbringshasit to thethe same resultfrontas invokingsetVisible(true). @seejava.awt.Window#showmoveToFront @seejava.awt.Window#toFrontsetSelected @seejava.awt.ComponentInternalFrameEvent#INTERNAL_FRAME_OPENED @see #setVisible
Sends this internal frame to the back. Places this internal frame at the bottom of the stacking order and makes the corresponding adjustment to other visibleClass JInternalFrame, void toFront()windowsinternal frames. @see java.awt.Window#toBack @see #moveToBack
Brings this internal frame to the front. Places this internal frame at the top of the stacking order and makes the corresponding adjustment to other visibleClass JInternalFrame, void updateUI()windowsinternal frames. @see java.awt.Window#toFront @see #moveToFront
Notification from theClass JInternalFrame, String IS_CLOSED_PROPERTYUIManagerthat theL&Flook and feel has changed. Replaces the current UI object with the latest version from theUIManager. @see JComponent#updateUI
Constrained property name indicating that the internal frame is closed.Class JInternalFrame, String IS_ICON_PROPERTY
Constrained property name indicating that the internal frame is iconified.Class JInternalFrame, String IS_MAXIMUM_PROPERTY
Constrained property name indicating that the internal frame is maximized.Class JInternalFrame, JDesktopIcon desktopIcon
The icon that is displayed whenClass JInternalFrame, Icon frameIconthethis internal frame isiconizediconified. @see #iconable
The icon shown in the top-left corner ofClass JInternalFrame, boolean iconablethethis internal frame.
The frame can "Class JInternalFrame, boolean isIconiconizediconified" (shrunk down and displayed as an icon-image). @see JInternalFrame.JDesktopIcon @see #setIconifiable
The frame has beenClass JInternalFrame, JRootPane rootPaneiconizediconified. @see #iconableisIcon()
TheClass JInternalFrame, boolean rootPaneCheckingEnabledJRootPaneinstance that manages thecontentPanecontent pane and optionalmenuBarmenu bar for this internal frame as well as theglassPaneglass pane. @see JRootPane @see RootPaneContainer
IfClass JInternalFrame, String titletruethen calls toaddandsetLayoutcause an exception to be thrown.
The title displayed inthethis internal frame's title bar.
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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component that displays a short string and an icon. @version 1.100 02110 12/0203/0001 @author Hans Muller
The class used to obtain the accessible role for this object.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
This isClass JLabel, void setUI(LabelUI)overridenoverridden to return false if the current Icon's Image is not equal to the passed in Imageimg. @see java.awt.image.ImageObserver @see java.awt.Component#imageUpdate(java.awt.Image int int int int int)
Sets the L&F object that renders this component. @param ui the LabelUI L&F object @see UIDefaults#getUI @beaninfoClass JLabel, void updateUI()expertbound: true hidden: true attribute: visualUpdate true description: TheL&FUI object thatrenders thisimplements thecomponentComponent's LookAndFeel.
NotificationResetsfromtheUIFactoryUI property tothata value from theL&Fcurrent lookhas changedand feel. @see JComponent#updateUI
JLayeredPaneadds depth to a JFC/Swing container allowing components to overlap each other when needed. AnIntegerobject specifies each component's depth in the container where higher-numbered components sit "on top" of other components. For task-oriented documentation and examples of using layered panes see How to Use a Layered Pane a section in The Java Tutorial.
For convenience
![]()
JLayeredPanedivides the depth-range into several different layers. Putting a component into one of those layers makes it easy to ensure that components overlap properly without having to worry about specifying numbers for specific depths:The
- DEFAULT_LAYER
- The standard layer where most components go. This the bottommost layer.
- PALETTE_LAYER
- The palette layer sits over the default layer. Useful for floating toolbars and palettes so they can be positioned above other components.
- MODAL_LAYER
- The layer used for modal dialogs. They will appear on top of any toolbars palettes or standard components in the container.
- POPUP_LAYER
- The popup layer displays above dialogs. That way the popup windows associated with combo boxes tooltips and other help text will appear above the component palette or dialog that generated them.
- DRAG_LAYER
- When dragging a component reassigning it to the drag layer ensures that it is positioned over every other component in the container. When finished dragging it can be reassigned to its normal layer.
JLayeredPanemethodsmoveToFront(Component)moveToBack(Component)andsetPositioncan be used to reposition a component within its layer. ThesetLayermethod can also be used to change the component's current layer.Details
JLayeredPanemanagesit'sits list of children likeContainerbut allows for the definition of a several layers within itself. Children in the same layer are managed exactly like the normalContainerobject with the added feature that when children components overlap children in higher layers display above the children in lower layers.Each layer is a distinct integer number. The layer attribute can be set on a
Componentby passing anIntegerobject during the add call.
For example:layeredPane.add(child JLayeredPane.DEFAULT_LAYER); or layeredPane.add(child new Integer(10));The layer attribute can also be set on a Component by callinglayeredPaneParent.setLayer(child 10)on theJLayeredPanethat is the parent of component. The layer should be set before adding the child to the parent.Higher number layers display above lower number layers. So using numbers for the layers and letters for individual components a representative list order would look like this:
5a 5b 5c 2a 2b 2c 1awhere the leftmost components are closest to the top of the display.A component can be moved to the top or bottom position within its layer by calling
moveToFrontormoveToBack.The position of a component within a layer can also be specified directly. Valid positions range from 0 up to one less than the number of components in that layer. A value of -1 indicates the bottommost position. A value of 0 indicates the topmost position. Unlike layer numbers higher position values are lower in the display.
Note: This sequence (defined by java.awt.Container) is the reverse of the layer numbering sequence. Usually though you will useHere are some examples using the method add(Component layer position): Calling add(5x 5 -1) results in:moveToFrontmoveToBackandsetLayer.5a 5b 5c 5x 2a 2b 2c 1aCalling add(5z 5 2) results in:5a 5b 5z 5c 5x 2a 2b 2c 1aCalling add(3a 3 7) results in:5a 5b 5z 5c 5x 3a 2a 2b 2c 1aUsing normal paint/event mechanics results in 1a appearing at the bottom and 5a being above all other components.Note: that these layers are simply a logical construct and LayoutManagers will affect all child components of this container without regard for layer settings.
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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @version 1.38 0436 02/0602/00 @author David Kloba
This class implements accessibility support for theJLayeredPaneclass. It provides an implementation of the Java Accessibility API appropriate to layered pane user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Class JLayeredPane, void moveToBack(Component)PrimativePrimitive method that determines the proper location to insert a new child based on layer and position requests. @param layer an int specifying the layer @param position an int specifying the position within the layer @return an int giving the (absolute) insertion-index @see #getIndexOf
Moves the component to the bottom of the components inClass JLayeredPane, void moveToFront(Component)it'sits current layer (position -1). @param c the Component to move @see #setPosition(Component int)
Moves the component to the top of the components inClass JLayeredPane, void setPosition(Component, int)it'sits current layer (position 0). @param c the Component to move @see #setPosition(Component int)
Moves the component topositionwithinit'sits current layer where 0 is the topmost position within the layer and -1 is the bottommost position.Note: Position numbering is defined by java.awt.Container and is the opposite of layer numbering. Lower position numbers are closer to the top (0 is topmost) and higher position numbers are closer to the bottom. @param c the Component to move @param position an int in the range -1..N-1 where N is the number of components in the component's current layer
A component that allows the user to select one or more objects from a list. A separate modelListModelrepresents 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.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.
74 04101 12/0603/0001 @author Hans Muller
This class implements accessibility support for theClass JList.AccessibleJList, Accessible getAccessibleAt(Point)JListclass. It provides an implementation of the Java Accessibility API appropriate to list user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Returns theClass JList.AccessibleJList, Accessible getAccessibleSelection(int)Accessiblechild contained at the local coordinatePointif one exists. Otherwise returnsnull. @return theAccessibleat the specified location if it exists
Returns an Accessible representing the specified selected item in the object. If there isn't a selection or there are fewer itemsselctedselected than the integer passed in the return value will benull. @param i the zero-based index of selected items @return an Accessible containing the selected item
Constructs aClass JList, void addSelectionInterval(int, int)JListthat displays the elements in the specified non-nullmodel. AllJListconstructors delegate to this one. @param dataModel the data model for this list @exception IllegalArgumentException ifdataModelisnull
Sets the selection to be the union of the specified interval with current selection. Both the anchor and lead indices are included. It's notClass JList, int getFirstVisibleIndex()neccessarynecessary for anchor to be less than lead. This is a convenience method that just delegates to theselectionModel. TheDefaultListSelectionModelimplementation will do nothing if eitheranchororleadare -1. Ifanchororleadare less than -1IndexOutOfBoundsExceptionis thrown. @param anchor the first index to add to the selection @param lead the last index to add to the selection @see ListSelectionModel#addSelectionInterval @see #setSelectionInterval @see #removeSelectionInterval @see #addListSelectionListener @exception IndexOutOfBoundsException if eitheranchororleadare less than -1
Returns the index of the first visible cell. The cell considered to be "first" depends on the list'sClass JList, int getLastVisibleIndex()componentOrientationproperty. If the orientation is horizontal left-to-right then the first visible cell is in theupperlist's upper-left corner.ofIf theJListorientationoris horizontal right-1to-left then the first visible cellifis in the list's upper-right corner. If nothing is visible or the list is empty a -1 is returned. Note thatthisthe returned cell may only be partially visible. @return the index of the first visible cell @see #getLastVisibleIndex @see JComponent#getVisibleRect
Returns the index of the last visible cell. The cell considered to be "last" depends on the list'sClass JList, Dimension getPreferredScrollableViewportSize()componentOrientationproperty. If the orientation is horizontal left-to-right then the last visible cell is in thelowerJList's lower-right corner.ofIf theJListorientationoris horizontal right-1to-left then the last visible cellifis in the JList's lower-left corner. If nothing is visible or the list is empty a -1 is returned. Note thatthisthe returned cell may only be partially visible. @return the index of the last visible cell @see #getLastVisibleIndexgetFirstVisibleIndex @see JComponent#getVisibleRect
Computes the size of the viewport needed to displayClass JList, int getScrollableBlockIncrement(Rectangle, int, int)visibleRowCountrows. This is trivial iffixedCellWidthandfixedCellHeightwere specified. Note that they can be specified implicitly with theprototypeCellValueproperty. IffixedCellWidthwasn't specified it's computed by finding the widest list element. IffixedCellHeightwasn't specified then we resort to heuristics:If the layout orientation is not
- If the model isn't empty we just multiply the height of the first row by
visibleRowCount.- If the model is empty (
JList.getModel().getSize() == 0) then we just allocate 16 pixels per visible row and 256 pixels for the width (unlessfixedCellWidthwas set) and hope for the best.VERTICALthan this will return the value fromgetPreferredSize. The currentListUIis expected to overridegetPreferredSizeto return an appropriate value. @return a dimension containing the size of the viewport needed to displayvisibleRowCountrows @see #getPreferredScrollableViewportSize @see #setPrototypeCellValue
Returns the distance to scroll to expose the next or previous block.Class JList, boolean getScrollableTracksViewportHeight()incrementForamountvertical scrolling we are using the follows rules:
- if scrolling down (
directionis greater than 0) the last visible element should become the first completely visible element- if scrolling up the first visible element should become the last completely visible element
- visibleRect.height if the list is empty
For horizontal scrolling if the list is layed out horizontally (the orientation is
VERTICAL_WRAPorHORIZONTAL_WRAP):or visibleRect.width if the list is layed out vertically or list is empty.
- if scrolling right (
directionis greater than 0) the next column should become the first visible column- if scrolling left and the beginning of the first column is visible the beginning of the previous column should become visible. If the beginning of the first column is not visible it should become visible.
Note that the value of
. @param visibleRect the visible rectangle @param orientation HORIZONTAL or VERTICAL @param direction if < 0 then scroll UP; if > 0 then scroll DOWN @return thevisibleRectmust be the equal tothis.getVisibleRect()visibleRect.heightblockor visibleRectincrement amount.width per the orientation@see Scrollable#getScrollableUnitIncrement @throws IllegalArgumentException if visibleRect isnullor orientation isn't one of SwingConstants.VERTICAL SwingConstants.HORIZONTAL.
Returns true if thisClass JList, boolean getScrollableTracksViewportWidth()JListis displayed in aJViewportand the viewport is taller thanJList's preferred height or if the layout orientation isVERTICAL_WRAPand the number of visible rows is < 0; otherwise returns false. If false then don't track the viewport's height. This allows vertical scrolling if theJViewportis itself embedded in aJScrollPane. @return true if viewport is taller thanJlist's preferred height otherwise false @see Scrollable#getScrollableTracksViewportHeight
Returns true if thisClass JList, Object[] getSelectedValues()JListis displayed in aJViewportand the viewport is wider thanJList's preferred width; or if the layout orientation isHORIZONTAL_WRAPand the visible row count is < 0; otherwise returns false. If false then don't track the viewport's width. This allows horizontal scrolling if theJViewportis itself embedded in aJScrollPane. @return true if viewport is wider than theJList's preferred width otherwise false @see Scrollable#getScrollableTracksViewportWidth
Returns an array of the values for the selected cells. The returned values are sorted in increasing index order. @return the selected values or an empty list if nothing is selected @see #isSelectedIndex @see #getModel @see #addListSelectionListenerClass JList, ListUI getUI()
Returns the look and feel (L&F) object that renders this component. @return the ListUI object that renders this component
Class JList, int locationToIndex(Point)Class JList, void removeSelectionInterval(int, int)ConvertsConvert a point inJListcoordinates to the closest index of the cell at that location.ReturnsTo-1determine ifthere's nothe cellatactually contains the specified location use a combination of this method andgetCellBounds. Returns -1 if the model is empty. @param location the coordinates of the cell relative toJList@return an integer -- the index of the cell at the given location or -1.
Sets the selection to be the set difference of the specified interval and the current selection. Both theClass JList, void setSelectionInterval(int, int)anchorindex0andleadindex1indices are removed. It's notneccessarynecessary foranchorindex0to be less thanleadindex1. This is a convenience method that just delegates to theselectionModel. TheDefaultListSelectionModelimplementation will do nothing if eitherindex0orindex1are -1. Ifindex0orindex1are less than -1IndexOutOfBoundsExceptionis thrown. @paramanchorindex0 the first index to remove from the selection @paramleadindex1 the last index to remove from the selection @exception IndexOutOfBoundsException if eitherindex0orindex1are less than -1 @see ListSelectionModel#removeSelectionInterval @see #setSelectionInterval @see #addSelectionInterval @see #addListSelectionListener
Selects the specified interval. Both theClass JList, void setSelectionMode(int)anchorandleadindices are included. It's notneccessarynecessary foranchorto be less thanlead. This is a convenience method that just delegates to theselectionModel. TheDefaultListSelectionModelimplementation will do nothing if eitheranchororleadare -1. Ifanchororleadare less than -1IndexOutOfBoundsExceptionis thrown. @param anchor the first index to select @param lead the last index to select @exception IndexOutOfBoundsException if eitheranchororleadare less than -1 @see ListSelectionModel#setSelectionInterval @see #addSelectionInterval @see #removeSelectionInterval @see #addListSelectionListener
Determines whether single-item or multiple-item selections are allowed. The followingClass JList, void setUI(ListUI)selectionModevalues are allowed:@param selectionMode an integer specifying the type of selections that are permissible @see #getSelectionMode @beaninfo description: The selection mode. enum: SINGLE_SELECTION ListSelectionModel.SINGLE_SELECTION SINGLE_INTERVAL_SELECTION ListSelectionModel.SINGLE_INTERVAL_SELECTION MULTIPLE_INTERVAL_SELECTION ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
ListSelectionModel.SINGLE_SELECTIONOnly one list index can be selected at a time. In this mode thesetSelectionIntervalandaddSelectionIntervalmethods are equivalent and only the second index argument is used.ListSelectionModel.SINGLE_INTERVAL_SELECTIONOne contiguous index interval can be selected at a time. In this modesetSelectionIntervalandaddSelectionIntervalare equivalent.ListSelectionModel.MULTIPLE_INTERVAL_SELECTIONIn this mode there's no restriction on what can be selected. This is the default.
Sets the look and feel (L&F) object that renders this component. @param ui the ListUI L&F object @see UIDefaults#getUI @beaninfo bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.
Class JList, void setVisibleRowCount(int)Sets the preferred number of rows in the list that can be displayed without aClass JList, void updateUI()scollbarscrollbar as determined by the nearestJViewportancestor if any. The value of this property only affects the value of theJList'spreferredScrollableViewportSize.The default value of this property is 8.
This is a JavaBeans bound property. @param visibleRowCount an integer specifying the preferred number of visible rows @see #getVisibleRowCount @see JComponent#getVisibleRect @see JViewport @beaninfo bound: true attribute: visualUpdate true description: The preferred number of cells that can be displayed without a scroll bar.
SetsResets the UI property with the"ListUI"value from the currentdefault UIFactory. This method is called by the JList constructor and to update the list'slook and feelat runtime. @see UIManager#getUI
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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer true description: A popup window containing menu items displayed in a menu bar. @version 1.145 02164 12/0903/01 @author Georges Saab @author David Karlton @author Arnaud Weber @see JMenuItem @see JSeparator @see JMenuBar @see JPopupMenu
This class implements accessibility support for theJMenuclass. It provides an implementation of the Java Accessibility API appropriate to menu user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
A listener class that watches for a popup window closing. When the popup is closing the listener deselects the menu.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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Creates a new menu item attached to the specifiedClass JMenu, void configurePropertiesFromAction(Action)Actionobject and appends it to the end of this menu. As ofJDK1.3 this is no longer the preferred method for addingActionsto a container. Instead it is recommended to configure a control with an action usingsetActionand then add that control directly to theContainer. @param a theActionfor the menu item to be added @see Action
Factory method which sets theClass JMenu, PropertyChangeListener createActionChangeListener(JMenuItem)ActionEventsource's properties according to values from theActioninstance. The properties which are set may differ for subclasses. By default the properties which get set areText Icon Enabled ToolTipText ActionCommandandMnemonic. @param a theActionfrom which to get the properties ornull@since 1.34 @see Action @see #setAction
Returns a properly configuredClass JMenu, JMenuItem createActionComponent(Action)PropertyChangeListenerwhich updates the control as changes to theActionoccur. As ofJDK1.3 this is no longer the preferred method for addingActions to aContainer. Instead it is recommended to configure a control with an action usingsetActionand then add that control directly to theContainer.
Factory method which creates theClass JMenu, void doClick(int)JMenuItemforActions added to theJMenu. As ofJDK1.3 this is no longer the preferred method. Instead it is recommended to configure a control with an action usingsetActionand then adding that control directly to theContainer. @param a theActionfor the menu item to be added @return the new menu item @see Action @since 1.3
Class JMenu, void fireMenuCanceled()ProgramaticallyProgrammatically performs a "click". This overrides the methodAbstractButton.doClickin order to make the menu pop up. @param pressTime indicates the number of milliseconds the button was pressed for
Notifies all listeners that have registered interest for notification on this event type. The event instance isClass JMenu, void fireMenuDeselected()lazilycreatedusing the parameters passed into the fire methodlazily. @exception Error if there is anulllistener @see EventListenerList
Notifies all listeners that have registered interest for notification on this event type. The event instance isClass JMenu, void fireMenuSelected()lazilycreatedusing the parameters passed into the fire methodlazily. @exception Error if there is anulllistener @see EventListenerList
Notifies all listeners that have registered interest for notification on this event type. The event instance isClass JMenu, Point getPopupMenuOrigin()lazilycreatedusing the parameters passed into the fire methodlazily. @exception Error if there is anulllistener @see EventListenerList
Computes the origin for theClass JMenu, void processFocusEvent(FocusEvent)JMenu's popup menu. This method uses Look and Feel properties namedMenu.menuPopupOffsetXMenu.menuPopupOffsetYMenu.submenuPopupOffsetXandMenu.submenuPopupOffsetYto adjust the exact location of popup. @return aPointin the coordinate space of the menu which should be used as the origin of theJMenu's popup menu @since 1.3
Processes focus events occurring on this component by dispatching them to any registeredClass JMenu, void processKeyEvent(KeyEvent)FocusListenerobjects.This method is not called unless
focus eventssuch asare enabledFocusEventfor this component.FOCUS_GAINEDFocus events are enabled when one of the following occurs:
- A
FocusListenerorobject is registered via.FocusEventaddFocusListenerFocus events are enabled via enableEvents.FOCUS_LOSTNote that if the event parameter is
the behavior is unspecified and may result in an exception. @param e thenullFocusEventfocus event @see java.awt.event.FocusEvent @see java.awt.event.FocusListener @see #addFocusListener @see #enableEvents @since JDK1.1
Processes key stroke eventsClass JMenu, void updateUI()for this menusuch as mnemonics and accelerators. @parameevt the key event to be processed
NotificationResetsfrom the UIFactory thattheL&F has changed. CalledUIto replace the UI withproperty with a value from thelatest versioncurrentfrom thelook andUIFactoryfeel. @see JComponent#updateUI
An implementation of a menu bar. You addJMenuobjects to the menu bar to construct a menu. When the user selects aJMenuobject its associatedJPopupMenuis displayed allowing the user to select one of theJMenuItemson it.For information and examples of using menu bars 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
JMenuBarkey 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer true description: A container for holding and displaying menus. @version 1.85 0492 12/0603/0001 @author Georges Saab @author David Karlton @author Arnaud Weber @see JMenu @see JPopupMenu @see JMenuItem
This class implements accessibility support for theJMenuBarclass. It provides an implementation of the Java Accessibility API appropriate to menu bar user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Class JMenuBar, void setUI(MenuBarUI)ReturnsChangestruethisJComponent's focus traversal keys toindicateCTRL+TAB and CTRL+SHIFT+TAB. Also preventsthatSortingFocusTraversalPolicyfrom considering descendants of thiscomponent managesJComponent when computing a focuseventstraversal cycle. @seeinternallyjava.awt.Component#setFocusTraversalKeys @see SortingFocusTraversalPolicy @returndeprecated As of 1.4 replaced byComponent.setFocusTraversalKeys(int Set)andtrueContainer.setFocusCycleRoot(boolean).
Sets the L&F object that renders this component. @param ui the new MenuBarUI L&F object @see UIDefaults#getUI @beaninfo bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.Class JMenuBar, void updateUI()
NotificationResetsfrom the UIFactory thattheL&F has changed. CalledUIto replace the UI withproperty with a value from thelatest versioncurrentfrom thelook andUIFactoryfeel. @see JComponent#updateUI
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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: An item which can be selected in a menu. @version 1.92 04106 12/0603/0001 @author Georges Saab @author David Karlton @see JPopupMenu @see JMenu @see JCheckBoxMenuItem @see JRadioButtonMenuItem
This class implements accessibility support for theClass JMenuItem.AccessibleJMenuItem, void stateChanged(ChangeEvent)JMenuItemclass. It provides an implementation of the Java Accessibility API appropriate to menu item user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Supports the change listener interface and fires propertychangechanges.
Creates aClass JMenuItem, constructor JMenuItem(Action)menuItemJMenuItemwith no set text or icon.
Creates a menu item whose properties are taken from theClass JMenuItem, constructor JMenuItem(Icon)ActionspecifiedsuppliedAction. @param a the action of theJMenuItem@since 1.3
Creates aClass JMenuItem, constructor JMenuItem(String)menuItemJMenuItemwithanthe specified icon. @param icon the icon of theMenuItem.JMenuItem
Creates aClass JMenuItem, constructor JMenuItem(String, Icon)menuItemJMenuItemwith the specified text. @param text the text of theMenuItem.JMenuItem
Creates aClass JMenuItem, constructor JMenuItem(String, int)menuJMenuItemitemwith thesuppliedspecified text and icon. @param text the text of theMenuItem.JMenuItem@param icon the icon of theMenuItem.JMenuItem
Creates aClass JMenuItem, void addMenuDragMouseListener(MenuDragMouseListener)menuItemJMenuItemwith the specified text and keyboard mnemonic. @param text the text of theMenuItem.JMenuItem@param mnemonic the keyboard mnemonic for theMenuItemJMenuItem
Adds aClass JMenuItem, void addMenuKeyListener(MenuKeyListener)MenuDragMouseListenerto the menu item. @param l theMenuDragMouseListenerto be added
Adds aClass JMenuItem, void configurePropertiesFromAction(Action)MenuKeyListenerto the menu item. @param l theMenuKeyListenerto be added
Factory method which sets theClass JMenuItem, PropertyChangeListener createActionPropertyChangeListener(Action)ActionEventsource's properties according to values from theActioninstance. The properties which are set may differ for subclasses. By defaultthe properties which get set are Textthis method sets the same properties asIconAbstractButton.configurePropertiesFromAction()plusAccelerator. @param a theActionfrom which to get the properties ornull@since 1.3 @see Action@see #setAction
Factory method which creates theClass JMenuItem, KeyStroke getAccelerator()PropertyChangeListenerused to update theActionEventsource as properties change on itsActioninstance. Subclasses may override this in order to provide their ownPropertyChangeListenerif the set of properties which should be kept up to date differsfrom.theNote that
PropertyChangeListenersshould avoid holding strong references to theActionEventsource as this may hinder garbage collection of theActionEventsource and all components in its containment hierarchy. @param a theActionfrom which to get the properties ornull@since 1.3 @see Action@see #setAction
Returns theClass JMenuItem, AccessibleContext getAccessibleContext()KeyStrokewhich serves as an accelerator for the menu item. @return aKeyStrokeobject identifying the accelerator key
Class JMenuItem, Component getComponent()GetsReturns theAccessibleContextassociated with thisJMenuItem. ForJMenuItemsJMenuItems theAccessibleContexttakes the form of anAccessibleJMenuItem. A new AccessibleJMenuItme instance is created if necessary. @return anAccessibleJMenuItemthat serves as theAccessibleContextof thisJMenuItem
Class JMenuItem, MenuElement[] getSubElements()ThisReturnsmethod returnsthejava.awt.Componentused to paint this object. The returned component will be used to convert events and detect if an event is inside a menu component. @return theComponentthat paints this menu item
This method returns an array containing the sub-menu components for this menu component. @return an array ofClass JMenuItem, String getUIClassID()MenuElementsMenuElements
Returns the suffix used to construct the name of the L&F classClass JMenuItem, void init(String, Icon)thatused torendersrender this component. @return the string "MenuItemUI" @see JComponent#getUIClassID @see UIDefaults#getUI
Class JMenuItem, void menuSelectionChanged(boolean)InitializeInitializes the menu item with the specified text and icon. @param text the text of theMenuItem.JMenuItem@param icon the icon of theMenuItem.JMenuItem
Called by theClass JMenuItem, String paramString()MenuSelectionManagerwhen theMenuElementis selected or unselected. @param isIncluded true if this menu item is on the part of the menu path that changed false if this menu is part of the a menu path that changed but this particular part of that path is still the same @see MenuSelectionManager#setSelectedPath(MenuElement[])
Returns a string representation of thisClass JMenuItem, void processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager)JMenuItem. 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 benull. @return a string representation of thisJMenuItem.
Class JMenuItem, void processMenuDragMouseEvent(MenuDragMouseEvent)ProcessProcesses a key event forwarded from theMenuSelectionManager. @param event A KeyEvent with source being the receiving component. @param componentPath The MenuElement path array to the receiving component. @param manager The MenuSelectionManager for the menu hierarchy. This method should process theKeyEventandchangechanges the menu selection if necessary by usingMenuSelectionManager's API.Note: you do not have to forward the event to sub-components. This is done automatically by the
MenuSelectionManager. @param e aKeyEvent@param path theMenuElementpath array @param manager theMenuSelectionManager
Class JMenuItem, void processMenuKeyEvent(MenuKeyEvent)HandleHandles mouse drag in a menu. @param e aMenuDragMouseEventobject
Class JMenuItem, void processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager)HandleHandles a keystroke in a menu. @param e aMenuKeyEventobject
Class JMenuItem, void removeMenuDragMouseListener(MenuDragMouseListener)ProcessProcesses a mouse event forwarded from theMenuSelectionManager. @param event A MouseEvent with source being the receiving component. @param componentPath The MenuElement path array to the receiving component. @param manager The MenuSelectionManager for themenu hierarchy. This method should process the MouseEventandchangechanges the menu selection if necessary by using theMenuSelectionManager's API.Note: you do not have to forward the event to sub-components. This is done automatically by the
MenuSelectionManager. @param e aMouseEvent@param path theMenuElementpath array @param manager theMenuSelectionManager
Removes aClass JMenuItem, void removeMenuKeyListener(MenuKeyListener)MenuDragMouseListenerfrom the menu item. @param l theMenuDragMouseListenerto be removed
Removes aClass JMenuItem, void setAccelerator(KeyStroke)MenuKeyListenerfrom the menu item. @param l theMenuKeyListenerto be removed
Class JMenuItem, void setEnabled(boolean)SetSets the key combination which invokes theMenumenuItemitem's action listeners without navigating the menu hierarchy. It is theUIsUI's responsibility todoinstall the correct action. Note that when the keyboard accelerator is typed it will work whether or not the menu is currently displayed. @param keyStroke theKeyStrokewhich will serve as an accelerator @beaninfo description: The keystroke combination which will invoke the JMenuItem's actionlisteners without navigating the menu hierarchy bound: true preferred: true
Class JMenuItem, void setUI(MenuItemUI)EnableEnables ordisabledisables the menu item. @param b true to enable the item @beaninfo description: Does the component react to user interaction bound: true preferred: true
Sets theL&Flook and feel object that renders this component. @param ui theMenuItemUIJMenuItemUIL&F object @see UIDefaults#getUI @beaninfodescriptionbound:The menu item's UI delegatetrueboundhidden: trueexpertattribute: visualUpdate truehiddendescription:trueThe UI object that implements the Component's LookAndFeel.
JOptionPanemakes it easy to pop up a standard dialog box that prompts users for a value or informs them of something. For information about usingJOptionPanesee How to Make Dialogs a section in The Java Tutorial.While the
JOptionPaneclass may appear complex because of the large number of methods almost all uses of this class are one-line calls to one of the staticshowXxxDialogmethods shown below:Each of these methods also comes in a
showConfirmDialog Asks a confirming question like yes/no/cancel. showInputDialog Prompt for some input. showMessageDialog Tell the user about something that has happened. showOptionDialog The Grand Unification of the above three. showInternalXXXflavor which uses an internal frame to hold the dialog box (see Multipl convenience methods have also been defined -- overloaded versions of the basic methods that use different parameter lists.All dialogs are modal. Each
showXxxDialogmethod blocks the current thread until the user's interaction is complete.
The basic appearance of one of these dialog boxes is generally similar to the picture at the right although the various look-and-feels are
icon message input value option buttons ultimatlyultimately responsible for the final result. In particular the look-and-feels will adjust the layout to accommodate the option pane'sComponentOrientationproperty.
Parameters:
The parameters to these methods follow consistent patterns:
- parentComponent
- Defines the
Componentthat is to be the parent of this dialog box. It is used in two ways: theFramethat contains it is used as theFrameparent for the dialog box and its screen coordinates are used in the placement of the dialog box. In general the dialog box is placed just below the component. This parameter may benullin which case a defaultFrameis used as the parent and the dialog will be centered on the screen (depending on the L&F).- message
- A descriptive message to be placed in the dialog box. In the most common usage message is just a
StringorStringconstant. However the type of this parameter is actuallyObject. Its interpretation depends on its type:
- Object[]
- An array of objects is interpreted as a series of messages (one per object) arranged in a vertical stack. The interpretation is recursive -- each object in the array is interpreted according to its type.
- Component
- The
Componentis displayed in the dialog.- Icon
- The
Iconis wrapped in aJLabeland displayed in the dialog.- others
- The object is converted to a
Stringby calling itstoStringmethod. The result is wrapped in aJLabeland displayed.- messageType
- Defines the style of the message. The Look and Feel manager may lay out the dialog differently depending on this value and will often provide a default icon. The possible values are:
ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEPLAIN_MESSAGE- optionType
- Defines the set of option buttons that appear at the bottom of the dialog box:
You aren't limited to this set of option buttons. You can provide any buttons you want using the options parameter.
DEFAULT_OPTIONYES_NO_OPTIONYES_NO_CANCEL_OPTIONOK_CANCEL_OPTION- options
- A more detailed description of the set of option buttons that will appear at the bottom of the dialog box. The usual value for the options parameter is an array of
Strings. But the parameter type is an array ofObjects. A button is created for each object depending on its type:
- Component
- The component is added to the button row directly.
- Icon
- A
JButtonis created with this as its label.- other
- The
Objectis converted to a string using itstoStringmethod and the result is used to label aJButton.- icon
- A decorative icon to be placed in the dialog box. A default value for this is determined by the
messageTypeparameter.- title
- The title for the dialog box.
- initialValue
- The default selection (input value).
When the selection is changed
setValueis invoked which generates aPropertyChangeEvent.If a
JOptionPanehas configured to all inputsetWantsInputthe bound propertyJOptionPane.INPUT_VALUE_PROPERTYcan also be listened to to determine when the user has input or selected a value.When one of the
showXxxDialogmethods returns an integer the possible values are:Examples:
- YES_OPTION
NO_OPTIONCANCEL_OPTIONOK_OPTIONorCLOSED_OPTION.Direct Use:
- Show an error dialog that displays the message 'alert':
JOptionPane.showMessageDialog(null "alert" "alert" JOptionPane.ERROR_MESSAGE);
- Show an internal information dialog with the message 'information':
JOptionPane.showInternalMessageDialog(frame "information"
"information" JOptionPane.INFORMATION_MESSAGE);
- Show an information panel with the options yes/no and message 'choose one':
JOptionPane.showConfirmDialog(null
"choose one" "choose one" JOptionPane.YES_NO_OPTION);
- Show an internal information dialog with the options yes/no/cancel and message 'please choose one' and title information:
JOptionPane.showInternalConfirmDialog(frame
"please choose one" "information"
JOptionPane.YES_NO_CANCEL_OPTION JOptionPane.INFORMATION_MESSAGE);
- Show a warning dialog with the options OK CANCEL title 'Warning' and message 'Click OK to continue':
Object[] options = { "OK" "CANCEL" };
JOptionPane.showOptionDialog(null "Click OK to continue" "Warning"
JOptionPane.DEFAULT_OPTION JOptionPane.WARNING_MESSAGE
null options options[0]);
- Show a dialog asking the user to type in a String:
String inputValue = JOptionPane.showInputDialog("Please input a value");
- Show a dialog asking the user to select a String:
Object[] possibleValues = { "First" "Second" "Third" };
Object selectedValue = JOptionPane.showInputDialog(null
"Choose one" "Input"
JOptionPane.INFORMATION_MESSAGE null
possibleValues possibleValues[0]);
To create and use anJOptionPanedirectly the standard pattern is roughly as follows:JOptionPane pane = new JOptionPane(arguments); pane.set.Xxxx(...); // Configure JDialog dialog = pane.createDialog(parentComponent title); dialog.show(); Object selectedValue = pane.getValue(); if(selectedValue == null) return CLOSED_OPTION; //If there is not an array of option buttons: if(options == null) { if(selectedValue instanceof Integer) return ((Integer)selectedValue).intValue(); return CLOSED_OPTION; } //If there is an array of option buttons: for(int counter = 0 maxCounter = options.length; counterFor the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JOptionPanekey 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see JInternalFrame @beaninfo attribute: isContainer true description: A component which implements standard dialog box controls. @version 1.61 0278 12/0903/01 @author James Gosling @author Scott Violet
This class implements accessibility support for theJOptionPaneclass. It provides an implementation of the Java Accessibility API appropriate to option pane user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Creates an instance ofClass JOptionPane, constructor JOptionPane(Object, int, int)JOptionPaneto display a message with the specified message type and the default options @param message theObjectto display @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE
Creates an instance ofClass JOptionPane, constructor JOptionPane(Object, int, int, Icon)JOptionPaneto display a message with the specified message type and options. @param message theObjectto display @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param optionType the options to display in the pane:DEFAULT_OPTIONYES_NO_OPTIONYES_NO_CANCEL_OPTIONOK_CANCEL_OPTION
Creates an instance ofClass JOptionPane, constructor JOptionPane(Object, int, int, Icon, Object[])JOptionPaneto display a message with the specified message type options and icon. @param message theObjectto display @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param optionType the options to display in the pane:DEFAULT_OPTIONYES_NO_OPTIONYES_NO_CANCEL_OPTIONOK_CANCEL_OPTION@param icon theIconimage to display
Creates an instance ofClass JOptionPane, constructor JOptionPane(Object, int, int, Icon, Object[], Object)JOptionPaneto display a message with the specified message type icon and options. None of the options is initially selected.The options objects should contain either instances of
Components (which are added directly) orStrings(which are wrapped in aJButton). If you provideComponents you must ensure that when theComponentis clicked it messagessetValuein the createdJOptionPane. @param message theObjectto display @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param optionType the options to display in the pane:DEFAULT_OPTIONYES_NO_OPTIONYES_NO_CANCEL_OPTIONOK_CANCEL_OPTION@param icon the; only meaningful if the options parameter is nullIconimage to display @param options the choices the user can select
Creates an instance ofClass JOptionPane, JDialog createDialog(Component, String)JOptionPaneto display a message with the specified message type icon and options with the initially-selected option specified. @param message theObjectto display @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param optionType the options to display in the pane:DEFAULT_OPTIONYES_NO_OPTIONYES_NO_CANCEL_OPTIONOK_CANCEL_OPTION@param icon the Icon image to display @param options the choices the user can select @param initialValue the choice that is initially selected; if; only meaningful if the options parameter is nullnullthen nothing will be initially selected; only meaningful ifoptionsis used
Creates and returns a newClass JOptionPane, AccessibleContext getAccessibleContext()JDialogwrappingthiscentered on theparentComponentin theparentComponent's frame.titleis the title of the returned dialog. The returnedJDialogwill not be resizable by the user however programs can invokesetResizableon theJDialoginstance to change this property. The returnedJDialogwill be set up such that once it is closed or the user clicks ontheone ofOK buttonthe buttons thedialogoptionpane's value property will bedisposedset accordingly and the dialog will be closed. Each time the dialog is made visible it will reset the option pane's value property toJOptionPane.UNINITIALIZED_VALUEto ensure the user's subsequent action closes the dialog properly. @param parentComponent determines the frame in which the dialog is displayed; if theparentComponenthas noFramea defaultFrameis used @param title the title string for the dialog @return a newJDialogcontaining this instance @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Class JOptionPane, Frame getFrameForComponent(Component)GetsReturns theAccessibleContextassociated with this JOptionPane. For option panes theAccessibleContexttakes the form of anAccessibleJOptionPane. A newAccessibleJOptionPaneinstance is created if necessary. @return an AccessibleJOptionPane that serves as the AccessibleContext of this AccessibleJOptionPane @beaninfo expert: true description: The AccessibleContext associated with this option pane
Returns the specified component'sClass JOptionPane, Object getInitialSelectionValue()Frame. @param parentComponent theComponentto check for aFrame@return theFramethat contains the component or the default frame if the component isnullor does not have a validFrameparent @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Returns theClass JOptionPane, Frame getRootFrame()initial-selectioninput value that is displayed as initially selected to the user. @return the initially selected value @see #setInitialSelectionValue @see #setSelectionValues
Returns theClass JOptionPane, Object[] getSelectionValues()Frameto use for the class methods in which a frame is not provided. @return the defaultFrameto use @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Returns the input selection values. @Class JOptionPane, Object getValue()paramreturn the array ofObjectsthe user can select @see #setSelectionValues
Returns the value the user has selected.Class JOptionPane, boolean getWantsInput()UNINITIALIZED_VALUEimplies the user has not yet made a choicenullmeans the user closed the window with out choosing anything. Otherwise the returned value will be one of the options defined in this object. @return theObjectchosen by the userUNINITIALIZED_VALUEif the user has not yet made a choice ornullif the user closed the window without making a choice @see #setValue
ReturnsClass JOptionPane, void setIcon(Icon)true if a parentComponent will betheprovided forvalue of theuser towantsInputinputproperty. @return true ifaanparentComponentinput component will be provided @see #setWantsInput
Sets the icon to display. If non-Class JOptionPane, void setInitialSelectionValue(Object)nulltheLooklook andFeelfeel does not provide an icon. @param icon theIconto display @see #getIcon @beaninfo preferred: true bound: true description: The option pane's type icon.
Sets theClass JOptionPane, void setInputValue(Object)initial selectioninput value that is initially displayed as selected to the user. Only used ifwantsInputis true. @param newValue the initially selected value @see #setSelectionValues @see #getInitialSelectionValue @beaninfo bound: true description: The option pane's initial selection value object.
Sets the input value that was selected or input by the userClass JOptionPane, void setMessageType(int)'s. Only used ifwantsInputis true. Note that this method is invoked internally by the option pane (in response to user action) and should generally not be called by client programs. To set the input-value initially displayed as selected to the user usesetInitialSelectionValue. @param newValue theObjectused toinitializedset the value that the user specified (usually in a text field) @see #setSelectionValues @see #setInitialSelectionValue @see #setWantsInput @see #getInputValue @beaninfo preferred: true bound: true description: The option pane's input value object.
Sets the option pane's message type. The message type is used by the Look and Feel to determine the icon to display (if not supplied) as well as potentially how to lay out theClass JOptionPane, void setOptionType(int)parentComponent. @param newType an integer specifying the kind of message to display:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@exception RuntimeException ifnewTypeis not one of the legal values listed above @see #getMessageType @beaninfo preferred: true bound: true description: The option pane's message type.
Sets the options to display. The option type is used by the Look and Feel to determine what buttons to show (unless options are supplied). @param newType an integer specifying the options the L&F is to display:Class JOptionPane, void setSelectionValues(Object[])DEFAULT_OPTIONYES_NO_OPTIONYES_NO_CANCEL_OPTIONorOK_CANCEL_OPTION@exception RuntimeException ifnewTypeis not one of the legal values listed above @see #getOptionType @see #setOptions @beaninfo preferred: true bound: true description: The option pane's option type.
Sets the input selection values for a pane that provides the user with a list of items to choose from. (The UI provides a widget for choosing one of the values.) AClass JOptionPane, void setWantsInput(boolean)nullvalue implies the user can input whatever they wish usually by means of aJTextField.Sets
wantsInputto true. UsesetInitialSelectionValueto specify the initially-chosen value. After the pane as been enabledinputValueis set to the value the user has selected. @param newValues an array ofObjectsthe user to be displayed (usually in a list or combo-box) from which the user can make a selection @see #setWantsInput @see #setInitialSelectionValue @see #getSelectionValues @beaninfo bound: true description: The option pane's selection values.
Sets theClass JOptionPane, int showConfirmDialog(Component, Object)wantsInputproperty. IfnewValueis true an input component (such as a text field or combo box) whose parent isparentComponentis provided to allow the user to input a value. IfgetSelectionValuesreturns a non-nullarray the input value is one of the objects in that array. Otherwise the input value is whatever the user inputs.This is a bound property. @see #setSelectionValues @see #setInputValue @beaninfo preferred: true bound: true description: Flag which allows the user to input a value.
Brings up aClass JOptionPane, int showConfirmDialog(Component, Object, String, int)modaldialog with the options Yes No and Cancel; with the title"Select an Option". @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message theObjectto display @return an integer indicating the option selected by the user @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Brings up aClass JOptionPane, int showConfirmDialog(Component, Object, String, int, int)modaldialog where the number of choices is determined by theoptionTypeparameter. @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message theObjectto display @param title the title string for the dialog @param optionType an int designating the options available on the dialog:YES_NO_OPTIONorYES_NO_CANCEL_OPTION@return an int indicating the option selected by the user @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Brings up aClass JOptionPane, int showConfirmDialog(Component, Object, String, int, int, Icon)modaldialog where the number of choices is determined by theoptionTypeparameter where themessageTypeparameter determines the icon to display. ThemessageTypeparameter is primarily used to supply a default icon from the Look and Feel. @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used. @param message theObjectto display @param title the title string for the dialog @param optionType an integer designating the options available on the dialog:YES_NO_OPTIONorYES_NO_CANCEL_OPTION@param messageType an integer designating the kind of message this is; primarily used to determine the icon from the pluggable Look and Feel:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@return an integer indicating the option selected by the user @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Brings up aClass JOptionPane, String showInputDialog(Component, Object)modaldialog with a specified icon where the number of choices is determined by theoptionTypeparameter. ThemessageTypeparameter is primarily used to supply a default icon from theLooklook andFeelfeel. @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param messageThethe Object to display @param title the title string for the dialog @param optionType an int designating the options available on the dialog:YES_NO_OPTIONorYES_NO_CANCEL_OPTION@param messageType an int designating the kind of message this is primarily used to determine the icon from the pluggable Look and Feel:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param icon the icon to display in the dialog @return an int indicating the option selected by the user @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Shows a question-message dialog requesting input from the user parented toClass JOptionPane, String showInputDialog(Component, Object, String, int)parentComponent. The dialog is displayedinon top of theComponent's frame and is usually positioned below theComponent. @param parentComponent the parentComponentfor the dialog @param message theObjectto display @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Shows a dialog requesting input from the user parented toClass JOptionPane, Object showInputDialog(Component, Object, String, int, Icon, Object[], Object)parentComponentwith the dialog having the titletitleand message typemessageType. @param parentComponent the parentComponentfor the dialog @param message theObjectto display @param title theStringto display in the dialog title bar @param messageType the type of message that is to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Prompts the user for input in a blocking dialog where the initial selection possible selections and all other options can be specified. The user will able to choose fromClass JOptionPane, String showInputDialog(Object)selectionValueswherenullimplies the user can input whatever they wish usually by means of aJTextField.initialSelectionValueis the initial value to prompt the user with. It is up to the UI to decide how best to represent theselectionValuesbut usually aJComboBoxJListorJTextFieldwill be used. @param parentComponent the parentComponentfor the dialog @param message theObjectto display @param title theStringto display in the dialog title bar @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param icon theIconimage to display @param selectionValues an array ofObjects that gives the possible selections @param initialSelectionValue the value used to initialize the input field @returnusersuser's input ornullmeaning the usercancelledcanceled the input @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Shows a question-message dialog requesting input from the user. The dialog uses the default frame which usually means it is centered on the screen. @param message theClass JOptionPane, int showInternalConfirmDialog(Component, Object)Objectto display @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Brings up an internal dialog panel with the options Yes No and Cancel; with the titleClass JOptionPane, int showInternalConfirmDialog(Component, Object, String, int)"Select an Option". @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message theObjectto display @return an integer indicating the option selected by the user
Brings up a internal dialog panel where the number of choices is determined by theClass JOptionPane, int showInternalConfirmDialog(Component, Object, String, int, int)optionTypeparameter. @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message the object to display in the dialog; aComponentobject is rendered as aComponent; aStringobject is rendered as a string; other objects are converted to aStringusing thetoStringmethod @param title the title string for the dialog @param optionType an integer designating the options available on the dialog:YES_NO_OPTIONorYES_NO_CANCEL_OPTION@return an integer indicating the option selected by the user
Brings up an internal dialog panel where the number of choices is determined by theClass JOptionPane, int showInternalConfirmDialog(Component, Object, String, int, int, Icon)optionTypeparameter where themessageTypeparameter determines the icon to display. ThemessageTypeparameter is primarily used to supply a default icon from the Look and Feel. @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message the object to display in the dialog; aComponentobject is rendered as aComponent; aStringobject is rendered as a string; other objects are converted to aStringusing thetoStringmethod @param title the title string for the dialog @param optionType an integer designating the options available on the dialog:YES_NO_OPTIONorYES_NO_CANCEL_OPTION@param messageType an integer designating the kind of message this is primarily used to determine the icon from the pluggable Look and Feel:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@return an integer indicating the option selected by the user
Brings up an internal dialog panel with a specified icon where the number of choices is determined by theClass JOptionPane, Object showInternalInputDialog(Component, Object, String, int, Icon, Object[], Object)optionTypeparameter. ThemessageTypeparameter is primarily used to supply a default icon from theLooklook andFeelfeel. @param parentComponent determines theFramein which the dialog is displayed; ifnullor if the parentComponent has no Frame a defaultFrameis used @param message the object to display in the dialog; aComponentobject is rendered as aComponent; aStringobject is rendered as a string; other objects are converted to aStringusing thetoStringmethod @param title the title string for the dialog @param optionType an integer designating the options available on the dialog:YES_NO_OPTIONorYES_NO_CANCEL_OPTION@param messageType an integer designating the kind of message this is primarily used to determine the icon from the pluggable Look and Feel:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param icon the icon to display in the dialog @return an integer indicating the option selected by the user
Prompts the user for input in a blocking internal dialog where the initial selection possible selections and all other options can be specified. The user will able to choose fromClass JOptionPane, void showInternalMessageDialog(Component, Object)selectionValueswherenullimplies the user can input whatever they wish usually by means of aJTextField.initialSelectionValueis the initial value to prompt the user with. It is up to the UI to decide how best to represent theselectionValuesbut usually aJComboBoxJListorJTextFieldwill be used. @param parentComponent the parentComponentfor the dialog @param message theObjectto display @param title theStringto display in the dialog title bar @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param icon theIconimage to display @param selectionValues an array ofObjectsthat gives the possible selections @param initialSelectionValue the value used to initialize the input field @returnusersuser's input ornullmeaning the usercancelledcanceled the input
Brings up an internal confirmation dialog panel. The dialog is aClass JOptionPane, void showInternalMessageDialog(Component, Object, String, int)modalinformation-message dialog titled "Message". @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message the object to display
Brings up an internal dialog panel that displays a message using a default icon determined by theClass JOptionPane, void showInternalMessageDialog(Component, Object, String, int, Icon)messageTypeparameter. @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message theObjectto display @param title the title string for the dialog @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE
Brings up an internal dialog panel displaying a message specifying all parameters. @param parentComponent determines theClass JOptionPane, int showInternalOptionDialog(Component, Object, String, int, int, Icon, Object[], Object)Framein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message theObjectto display @param title the title string for the dialog @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param icon an icon to display in the dialog that helps the user identify the kind of message that is being displayed
Brings up an internal dialog panel with a specified icon where the initial choice isClass JOptionPane, void showMessageDialog(Component, Object)dermineddetermined by theinitialValueparameter and the number of choices is determined by theoptionTypeparameter.If
optionTypeisYES_NO_OPTIONorYES_NO_CANCEL_OPTIONand theoptionsparameter isnullthen the options are supplied by the Look and Feel.The
messageTypeparameter is primarily used to supply a default icon from theLooklook andFeelfeel. @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message the object to display in the dialog; aComponentobject is rendered as aComponent; aStringobject is rendered as a string. Other objects are converted to aStringusing thetoStringmethod @param title the title string for the dialog @param optionType an integer designating the options available on the dialog:YES_NO_OPTIONorYES_NO_CANCEL_OPTION@param messageType an integer designating the kind of message this is; primarily used to determine the icon from the pluggable Look and Feel:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param icon the icon to display in the dialog @param options an array of objects indicating the possible choices the user can make; if the objects are components they are rendered properly; non-Stringobjects are rendered using theirtoStringmethods; if this parameter isnullthe options are determined by the Look and Feel @param initialValue the object that represents the default selection for the dialog; only meaningful ifoptionsis used; can benull@return an integer indicating the option chosen by the user orCLOSED_OPTIONif the user closed the Dialog
Brings upClass JOptionPane, void showMessageDialog(Component, Object, String, int)a modalan information-message dialog titled "Message". @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message theObjectto display @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Brings up a dialog that displays a message using a default icon determined by theClass JOptionPane, void showMessageDialog(Component, Object, String, int, Icon)messageTypeparameter. @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message theObjectto display @param title the title string for the dialog @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Brings up a dialog displaying a message specifying all parameters. @param parentComponent determines theClass JOptionPane, int showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object)Framein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message theObjectto display @param title the title string for the dialog @param messageType the type of message to be displayed:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param icon an icon to display in the dialog that helps the user identify the kind of message that is being displayed @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Brings up aClass JOptionPane, int CLOSED_OPTIONmodaldialog with a specified icon where the initial choice isdermineddetermined by theinitialValueparameter and the number of choices is determined by theoptionTypeparameter.If
optionTypeisYES_NO_OPTIONorYES_NO_CANCEL_OPTIONand theoptionsparameter isnullthen the options are supplied by theLooklook andFeelfeel.The
messageTypeparameter is primarily used to supply a default icon from theLooklook andFeelfeel. @param parentComponent determines theFramein which the dialog is displayed; ifnullor if theparentComponenthas noFramea defaultFrameis used @param message theObjectto display @param title the title string for the dialog @param optionType an integer designating the options available on the dialog:YES_NO_OPTIONorYES_NO_CANCEL_OPTION@param messageType an integer designating the kind of message this is primarily used to determine the icon from the pluggable Look and Feel:ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEorPLAIN_MESSAGE@param icon the icon to display in the dialog @param options an array of objects indicating the possible choices the user can make; if the objects are components they are rendered properly; non-Stringobjects are rendered using theirtoStringmethods; if this parameter isnullthe options are determined by the Look and Feel.@param initialValue the object that represents the default selection for the dialog; only meaningful ifoptionsis used; can benull@return an integer indicating the option chosen by the user orCLOSED_OPTIONif the user closed theDialogdialog @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Return value from class method if user closes window without selecting anything more than likely this should be treated as either aClass JOptionPane, int DEFAULT_OPTIONCANCEL_OPTIONorNO_OPTION.
TypeClass JOptionPane, String ICON_PROPERTYmeaning Lookused forand Feel should not supply any options -- only use the options from the JOptionPaneshowConfirmDialog.
Bound property name for icon.
Class JOptionPane, String INITIAL_SELECTION_VALUE_PROPERTYBound property name for initialSelectionValue.
Class JOptionPane, String INITIAL_VALUE_PROPERTYClass JOptionPane, String INPUT_VALUE_PROPERTYBoundsBound property name forinitialValue.
Bound property name for inputValue.
Class JOptionPane, String MESSAGE_PROPERTYBound property name for message.
Class JOptionPane, String MESSAGE_TYPE_PROPERTYClass JOptionPane, int OK_CANCEL_OPTIONBoundsBound property name fortype.
Type used for showConfirmDialog.
Class JOptionPane, String OPTIONS_PROPERTYClass JOptionPane, String OPTION_TYPE_PROPERTYBoundsBound propertynamername foroption.
Bound property name for optionType.
Class JOptionPane, String SELECTION_VALUES_PROPERTYBound property name for selectionValues.
Class JOptionPane, String VALUE_PROPERTYClass JOptionPane, String WANTS_INPUT_PROPERTYBoundsBound property name forvalue.
Bound property name for wantsInput.
Class JOptionPane, int YES_NO_CANCEL_OPTIONType used for showConfirmDialog.
Class JOptionPane, int YES_NO_OPTIONType used for showConfirmDialog.
Class JOptionPane, Object initialSelectionValueInitial value to select in selectionValues.
Class JOptionPane, Object initialValueValue that should beClass JOptionPane, int optionTypeinitialyinitially selected inoptions.
Option type one ofClass JOptionPane, Object valueDEFAULT_OPTIONYES_NO_OPTIONYES_NO_CANCEL_OPTIONorOK_CANCEL_OPTION.
Currently selected value will be a valid option orUNINITIALIZED_VALUEornull.
JPanelis a generic lightweight container. For examples and task-oriented documentation for JPanel see How to Use Panels 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo description: A generic lightweight container. @version 1.37 0442 12/0603/0001 @author Arnaud Weber @author Steve Wilson
This class implements accessibility support for theJPanelclass. It provides an implementation of the Java Accessibility API appropriate to panel user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Class JPanel, constructor JPanel(boolean)CreateCreates a newJPanelwith a double buffer and a flow layout.
Class JPanel, void updateUI()CreateCreates a newJPanelwithFlowLayoutand the specified buffering strategy. IfisDoubleBufferedis true theJPanelwill use a double buffer. @param layout the LayoutManager to use @param isDoubleBuffered a boolean true for double-buffering which uses additional memory space to achieve fast flicker-free updates
NotificationResetsfromtheUIFactoryUI property withthata value from theL&Fcurrent lookhas changedand feel. @see JComponent#updateUI
JPasswordFieldis a lightweight component that allows the editing of a single line of text where the view indicates something was typed but does not show the original characters. You can find further information and examples in How to Use Text Fields a section in The Java Tutorial.
JPasswordFieldis intended to be source-compatible withjava.awt.TextFieldused withechoCharset. It is providedseperatelyseparately to make it easier to safely change theuiUI for theJTextFieldwithout affecting password entries.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the JPasswordField key 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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: Allows the editing of a line of text but doesn't show the characters. @author Timothy Prinzing @version 1.42 0449 12/0603/0001
This class implements accessibility support for theJPasswordFieldclass. It provides an implementation of the Java Accessibility API appropriate to password field user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Constructs a newClass JPasswordField, constructor JPasswordField(Document, String, int)JPasswordFieldwith a default documentnullstarting text string and 0 column width.
Constructs a newClass JPasswordField, constructor JPasswordField(String)JPasswordFieldthat uses the given text storage model and the given number of columns. This is the constructor through which the other constructors feed. The echo character is set to '*'. If the document model isnulla default one will be created. @param doc the text storage to use @param txt the text to be displayednullif none @param columns the number of columns to use to calculate the preferred width >= 0. If; if columns is set to zero the preferred width will be whatever naturally results from the component implementation.
Constructs a newClass JPasswordField, constructor JPasswordField(String, int)JPasswordFieldinitialized with the specified text. The document model is set to the default and the number of columns to 0. @param text the text to be displayednullif none
Constructs a newClass JPasswordField, constructor JPasswordField(int)JPasswordFieldinitialized with the specified text and columns. The document model is set to the default. @param text the text to be displayednullif none @param columns the number of columns >= 0
Constructs a new emptyClass JPasswordField, void copy()JPasswordFieldwith the specified number of columns. A default model is created and the initial string is set tonull. @param columns the number of columns >= 0
Class JPasswordField, void cut()NormallyInvokestransfersprovideErrorFeedbackon the current look and feel which typically initiates an error beep. The normal behavior of transferring the currently selected range in the associated text model to the system clipboard and leaving the contentsinfrom thetextmodel. Thisis nota good thingacceptable for a password fieldand is reimplemented to simply beep.
Class JPasswordField, boolean echoCharIsSet()NormallyInvokestransfersprovideErrorFeedbackon the current look and feel which typically initiates an error beep. The normal behavior of transferring the currently selected range in the associated text model to the system clipboard and removing the contents from the model.Thisis nota goodacceptablethingfor a password fieldand is reimplemented to simply beep.
Returns true if this JPasswordField has a character set for echoing. A character is considered to be set if the echo character is not 0. @return true if a character is set for echoing @see #setEchoChar @see #getEchoChar
Class JPasswordField, AccessibleContext getAccessibleContext()Class JPasswordField, char[] getPassword()GetsReturns theAccessibleContextassociated with thisJPasswordField. For password fields theAccessibleContexttakes the form of anAccessibleJPasswordField. A newAccessibleJPasswordFieldinstance is created if necessary. @return anAccessibleJPasswordFieldthat serves as theAccessibleContextof thisJPasswordField
Returns the text contained in thisClass JPasswordField, String getText()TextComponent. If the underlying document isnullwill give aNullPointerException. For stronger security it is recommended that the returned character array be cleared after use by setting each character to zero. @return the text
Returns the text contained in thisClass JPasswordField, String getText(int, int)TextComponent. If the underlying document isnullwill give aNullPointerException.For security reasons this method is deprecated. Use the
* getPasswordmethod instead. @deprecated As of Java 2 platform v1.2 replaced bygetPassword. @return the text()
Fetches a portion of the text represented by the component. Returns an empty string if length is 0.Class JPasswordField, String getUIClassID()For security reasons this method is deprecated. Use the
getPasswordmethod instead. @deprecated As of Java 2 platform v1.2 replaced bygetPassword. @param offs the offset >= 0 @param len the length >= 0 @return the text @exception BadLocationException if the offset or length are invalid()
Returns the name of the L&F class that renders this component. @return the string "PasswordFieldUI" @see JComponent#getUIClassID @see UIDefaults#getUIClass JPasswordField, String paramString()
Returns a string representation of thisClass JPasswordField, void setEchoChar(char)JPasswordField. 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 benull. @return a string representation of thisJPasswordField.
Sets the echo character for thisJPasswordField. Note that this is largely a suggestionto the viewsinceasthe view that gets installed can use whatever graphic techniques it desires to represent the field. Setting a value of 0unsetsindicates that you wish to see theechotextcharacteras it is typed similar to the behavior of a standardJTextField. @param c the echo character to display @see #echoCharIsSet @see #getEchoChar @beaninfo description: character to display in place of the real characters attribute: visualUpdate true
An implementation of a popup menu -- a small window that pops up and displays a series of choices. AClass JPopupMenu, JMenuItem createActionComponent(Action)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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.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.149 11169 12/2705/0001 @author Georges Saab @author David Karlton @author Arnaud Weber
Factory method which creates theClass JPopupMenu, boolean getDefaultLightWeightPopupEnabled()JMenuItemforActionsadded to theJPopupMenu. As of JDK 1.3 this is no longer the preferred method instead it is recommended to configure a control with an action usingsetActionand then adding that control directly to theContainer. @param a theActionfor the menu item to be added @return the new menu item @see Action @since 1.3
Class JPopupMenu, void insert(Action, int)ReturnsGetstrue if this istheadefaultLightWeightPopupEnabledlight weight popup component falseproperty which by default isotherwisetrue. @return the value of theproperty @see #setDefaultLightWeightPopupEnabledlightWeightPopupEnableddefaultLightWeightPopupEnabled
Inserts a menu item for the specifiedClass JPopupMenu, boolean isLightWeightPopupEnabled()Actionobject at a given position. @param a theActionobject to insert @param index specifies the position at which to insert theActionwhere 0 is the first @exception IllegalArgumentException ifindex<0 @see Action
Class JPopupMenu, void paintBorder(Graphics)Returns trueGets theiflightWeightPopupEnabledlight weight (all-Java) popups are in use or false if heavy weight (native peer) popups are being usedproperty. @returntrue ifthelight weight popupsvalue of thearelightWeightPopupEnabledinpropertyuse false@seeotherwise#setLightWeightPopupEnabled
Paints the popup menu's border if theClass JPopupMenu, void setDefaultLightWeightPopupEnabled(boolean)property isBorderPaintedborderPaintedtrue. @param g theGraphicsobject @see JComponent#paint @see JComponent#setBorder
Sets the default valueClass JPopupMenu, void setLightWeightPopupEnabled(boolean)forof thelightWeightPopupEnabledproperty.Lightweight popup windows are more efficient than heavy weight windows but light weight and heavy weight components do not mix well in a GUI and in that situation a heavy weight may be required.@param aFlagtrueifthe popuppopupsiscantobelight weightlightweight otherwisefalse@see #getDefaultLightWeightPopupEnabled @see #setLightWeightPopupEnabled
WhenSetsdisplayingthe value of thepopuplightWeightPopupEnabledproperty which by default is. By default when a look and feel displays aJPopupMenutruechoosespopup it can choose to use alightlightweightweight(all-Java) popup.if itLightweight popupfits.windowsThis method allows you toare more efficient than heavyweightdisable(nativethispeer)feature.windows butYou have tolightweight and heavyweight components dodisablenotitmix well inifa GUI. If your application mixeslight weightlightweight andheavy weightsheavyweight components you should disable lightweight popups.@paramSomeaFlag true if the popup islook and feels might always usetoheavyweight popups no matter what the valuebeoflightthis property.weight@paramotherwiseaFlagfalseto 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 ofan eventsome work by displaying its percentage of completion and possibly a textual display of this percentage.
ForTofurtherindicatedocumentationthat 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.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.79 0289 12/0903/01 @author Michael C. Albers @author Kathy Walrath
This class implements accessibility support for theClass JProgressBar.AccessibleJProgressBar, AccessibleRole getAccessibleRole()JProgressBarclass. It provides an implementation of the Java Accessibility API appropriate to progress bar user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Class JProgressBar.AccessibleJProgressBar, AccessibleStateSet getAccessibleStateSet()GetGets the role of this object. @return an instance of AccessibleRole describing the role of the object
Class JProgressBar.AccessibleJProgressBar, AccessibleValue getAccessibleValue()GetGets the state set of this object. @return an instance of AccessibleState containing the current state of the object @see AccessibleState
Class JProgressBar.AccessibleJProgressBar, Number getCurrentAccessibleValue()GetGets theAccessibleValueassociated with this object. In the implementation of the Java Accessibility API for this classreturnreturns this object which is responsible for implementing theAccessibleValueinterface on behalf of itself. @return this object
Class JProgressBar.AccessibleJProgressBar, Number getMaximumAccessibleValue()GetGets the accessible value of this object. @returnThethe current value of this object.
Class JProgressBar.AccessibleJProgressBar, Number getMinimumAccessibleValue()GetGets the maximum accessible value of this object. @returnThethe maximum value of this object.
Class JProgressBar.AccessibleJProgressBar, boolean setCurrentAccessibleValue(Number)GetGets the minimum accessible value of this object. @returnThethe minimum value of this object.
SetSets the value of this object as aNumber. @returnTruetrueif the value was set.
Creates a horizontal progress barClass JProgressBar, constructor JProgressBar(BoundedRangeModel).The default orientation for progress bars isthat displays a border but no progressJProgressBar.HORIZONTALstring.By defaultThethe String is set toinitial and minimum values arenull0 and theStringPainted is not painted. The bordermaximum ispainted by default. Uses the defaultMinimum (0) and defaultMaximum (100).Uses@seethe defaultMinimum#setOrientationfor@seethe#setBorderPaintedinitial@seevalue#setStringPaintedof@seethe#setStringprogress@seebar.#setIndeterminate
Creates a horizontal progress barClass JProgressBar, constructor JProgressBar(int)the default orientation. Bythatdefaultuses theString isspecifiedsetmodel tonullholdandtheStringPainted isprogressnotbar'spainteddata.TheBy default a border is paintedbybutdefault.aUses the specifiedprogress string isBoundedRangeModelnot.which@paramholdsnewModel theminimumdatavalue andmodel formaximum.the@seeprogressBoundedRangeModelbar @see #setOrientation @see #setBorderPainted @see #setStringPainted @see #setString @see #setIndeterminate
Creates a progress bar with the specified orientation which can be eitherClass JProgressBar, constructor JProgressBar(int, int)JProgressBar.VERTICALorJProgressBar.HORIZONTAL. By defaultthe Stringa border isset topaintednullbutand the StringPainteda progress string is notpainted. Theborder is painted byinitialdefault.andUses the defaultMinimumminimum values are(0)anddefaultMaximumthe(100).maximumUsesisthe100.defaultMinimum@paramfororient theinitialdesiredvalueorientation of the progress bar.@see #setOrientation @see #setBorderPainted @see #setStringPainted @see #setString @see #setIndeterminate
Creates a horizontal progress barClass JProgressBar, constructor JProgressBar(int, int, int)whichwithisthe specified minimum and maximum. Sets thedefaultinitial value of the progress bar to the specified minimum. By defaultthe Stringa border issetpaintedtobut a progress string is not. ThenullBoundedRangeModelandthat holds theStringPaintedprogressisbar'snotdatapainted.handlesThe border is painted byany issues that may arisedefault.fromUses the specifiedimproperly setting the minimum initial and maximum.valuesUseson thespecifiedprogress bar. @param min the minimumforvalue of theinitialprogress bar @param max the maximum value of the progress bar.@see BoundedRangeModel @see #setOrientation @see #setBorderPainted @see #setStringPainted @see #setString @see #setIndeterminate
Creates a progress bar using the specified orientation minimum and maximum. By defaultClass JProgressBar, void addChangeListener(ChangeListener)the Stringa border isset topaintednullbutand the StringPainteda progress string is notpainted. The border is painted by default. Sets theinitalinitial value of the progress bar to the specified minimum. TheBoundedRangeModelthatsitsholdsunderneaththe progress bar's data handles any issues that mayarrisearise from improperly setting the minimumvalueinitial and maximum values on the progress bar. @param orient the desired orientation of the progress bar @param min the minimum value of the progress bar @param max the maximum value of the progress bar @see BoundedRangeModel @see #setOrientation @see #setBorderPainted @see #setStringPainted @see #setString @see #setIndeterminate
AddsClass JProgressBar, void fireStateChanged()athe specifiedChangeListenerto thebuttonprogress bar. @param l theChangeListenerto add
Class JProgressBar, AccessibleContext getAccessibleContext()NotifyNotifies all listeners that have registered interestforinnotification on this event typeChangeEvents. The event instance islazilycreatedusing the parameters passed into the fireifmethodnecessary. @see EventListenerList
Gets theClass JProgressBar, int getMaximum()AccessibleContextassociated with thisJProgressBar. For progress bars theAccessibleContexttakes the form of anAccessibleJProgressBar. A newAccessibleJProgressBarinstance is created if necessary. @return anAccessibleJProgressBarthat serves as theAccessibleContextof thisJProgressBar@beaninfo expert: true description: The AccessibleContext associated with this ProgressBar.
Returns theClass JProgressBar, int getMinimum()modelprogress bar's maximum value which is stored in the progress bar'sBoundedRangeModel. By defaultthisthe maximum value is100. @returnan int --themodelprogress bar's maximum value @see #setMaximum @see BoundedRangeModel#getMaximum
Returns theClass JProgressBar, BoundedRangeModel getModel()modelprogress bar's minimum value which is stored in the progress bar'sBoundedRangeModel. By defaultthisthe minimum value is0. @returnan int --themodelprogress bar's minimum value @see #setMinimum @see BoundedRangeModel#getMinimum
Returns the data model used byClass JProgressBar, int getOrientation()thethis progressJProgressBarbar. @return theBoundedRangeModelcurrently in use @see BoundedRangeModel
ReturnsClass JProgressBar, double getPercentComplete()JProgressBar.VERTICALorJProgressBar.HORIZONTALdepending on the orientation of the progress bar. The default orientation isHORIZONTAL. @returnHORIZONTALorVERTICAL@see #setOrientation
Returns theClass JProgressBar, String getString()percentage/percent complete for the progress bar. Note thatas a doublethis number is between 0.000 and 1.000. @return the percent complete for this progress bar.
Returns the current value of theClass JProgressBar, ProgressBarUI getUI()Progress Stringprogress string. If you are providing a customProgressprogress stringString viaby overriding this methodyou will wantmaketo ensure thatsure your implementationyou callcallssetStringbefore()you callcallingsuper.getString. @return the value of the percent string @see #setString();
Returns theClass JProgressBar, String getUIClassID()L&Flook-and-feel object that renders this component. @return theProgressBarUIobject that renders this component
Returns the name of theClass JProgressBar, int getValue()L&Flook-and-feel class that renders this component. @return the string "ProgressBarUI" @see JComponent#getUIClassID @see UIDefaults#getUI @beaninfo expert: true description: A string that specifies the name of theL&Flook-and-feel class.
Returns theClass JProgressBar, boolean isBorderPainted()modelprogress bar's current value which is stored in the progress bar'sBoundedRangeModel. The value is always between themodel'sminimum and maximum values inclusive. By default the valueequalsis initialized to be equal to the minimum value. @return the current value of the progress bar @see #setValue @see BoundedRangeModel#getValue
ReturnsClass JProgressBar, boolean isStringPainted()true if the progress bar has a border or false if it does not. By default this is true -theprogress bar paints it'sborderPaintedborderproperty. @returnwhethertheprogress bar paintsvalue of theitsborderPaintedborderproperty @see #setBorderPainted @beaninfo description: Does the progress bar paint its border
ReturnsClass JProgressBar, void paintBorder(Graphics)true if the progress bar will render a string ontotherepresentationvalue of theprogress bar. Returns false if it will not do this rendering. The default is false - the progress bar does not draw the string bystringPainteddefaultproperty. @returnwhethertheprogress bar rendersvalue of theastringPaintedstringproperty @see #setStringPainted @see #setString
Class JProgressBar, String paramString()PaintPaints the progress bar's border ifBorderPaintedtheborderPaintedproperty istrue. @param g theGraphicscontext within which to paint the border @see #paint @see #setBorder @see #isBorderPainted @see #setBorderPainted
Returns a string representation of thisClass JProgressBar, void removeChangeListener(ChangeListener)JProgressBar. This method is intended to be used only for debugging purposesand.theThe content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return a string representation of thisJProgressBar.
Removes aClass JProgressBar, void setBorderPainted(boolean)ChangeListenerfrom thebuttonprogress bar. @param l theChangeListenerto remove
SetsClass JProgressBar, void setMaximum(int)whethertheborderPaintedproperty which istrueif the progress bar should paint its border.ByThe default value for this property istrue.- paint theSome look andborderfeels might not implement painted borders; they will ignore this property. @param btrueif the progress barpaintsshould paint its border; otherwisefalse@see #isBorderPainted @beaninfo bound: true attribute: visualUpdate true description: Whether the progress bar should paint its border.
Sets theClass JProgressBar, void setMinimum(int)modelprogress bar's maximum value (stored in the progress bar's data model) toxn. The underlyingBoundedRangeModelwillhandlehandles any mathematical issuesarrisingarising from assigning faulty values.
Notifies anyIf thelistenersmaximum value isifdifferent from thedataprevious maximum all change listenerschangesare notified. @paramxn the new maximum @see #getMaximum @see #addChangeListener @see BoundedRangeModel#setMaximum @beaninfo preferred: true description: Themodelprogress bar's maximum value.
Sets theClass JProgressBar, void setModel(BoundedRangeModel)modelprogress bar's minimum value (stored in the progress bar's data model) toxn. Theunderlyingdata model (aBoundedRangeModelwillinstance)handlehandles any mathematical issuesarrisingarising from assigning faulty values.
Notifies anyIf thelistenersminimum value is differentiffrom thedatapreviouschangesminimum all change listeners are notified. @paramxn the new minimum @see #getMinimum @see #addChangeListener @see BoundedRangeModel#setMinimum @beaninfo preferred: true description: Themodelprogress bar's minimum value.
Sets the data model used by theClass JProgressBar, void setOrientation(int)JProgressBar. @param newModel theBoundedRangeModelto use @see BoundedRangeModel @beaninfo expert: true description: The data model used by the JProgressBar.
Sets the progress bar's orientation toClass JProgressBar, void setString(String)newOrientationwhich must beJProgressBar.VERTICALorJProgressBar.HORIZONTAL. The default orientation isHORIZONTAL. @param newOrientationHORIZONTALorVERTICAL@exception IllegalArgumentException ifnewOrientationis an illegal value @see #getOrientation @beaninfo preferred: true bound: true attribute: visualUpdate true description: Set the progress bar's orientation.
Sets the value of theClass JProgressBar, void setStringPainted(boolean)Progress Stringprogress string. By default thisStringstring isset tonull. If youare providinghave provided a customProgress String viaprogressthis method you will wantstring and want to revert toensurethethatbuilt-inyou callbehavior setsetString()thebefore you callstring back togetString()null. If youhave providedare providing a customStringprogressand want to revert to thestring by overriding this method makebuilt-insurebehaviorthatsetyou callsetStringbefore callinggetString. The progress string is painted only if theStringisStringPaintedback tomethod returns. @param s the value of the percent string @see #getString @see #setStringPainted @see #isStringPainted @beaninfo bound: true attribute: visualUpdate true description:nulltrueWhetherSpecifies the progressbar will render astringpercent stringto paint
Sets the value of theClass JProgressBar, void setUI(ProgressBarUI)stringPaintedproperty which determines whether the progress barwillshould render a progress string. The default isfalse: no string is painted. Some look and feels might not support progress strings or might support them only when the progress bar is in determinate mode. @param btrueif the progress barwillshould render a string.@see #isStringPainted @see #setString @beaninfo bound: true attribute: visualUpdate true description: Whether the progress barwillshould render a string.
Sets theClass JProgressBar, void setValue(int)L&Flook-and-feel object that renders this component. @param uitheaProgressBarUIobject @see UIDefaults#getUI @beaninfoL&Fexpertbound: true hidden: true attribute: visualUpdate true description: TheProgressBarUI implementationUI object thatdefinesimplements theprogress barComponent'slook and feelLookAndFeel.
Sets theClass JProgressBar, void updateUI()modelprogress bar's current value (stored in the progress bar's data model) toxn. Theunderlyingdata model (aBoundedRangeModelwillinstance)handlehandles any mathematical issuesarrisingarising from assigning faulty values.If the new value is different from the previous value all change listeners are notified. @param
xn the new value @see #getValue @see BoundedRangeModel#setValue @beaninfo preferred: true description: Themodelprogress bar's current value.
Class JProgressBar, ChangeEvent changeEventNotificationResetsfrom the UIFactory thattheL&F has changed.UICalledproperty toreplace theaUI withvalue from thelatest versioncurrentfrom the UIFactorylook and feel. @see JComponent#updateUI
Only one ChangeEvent is needed per instance since the event's only interesting property is the immutable source which is the progress bar.
Class JProgressBar, BoundedRangeModel modelTheClass JProgressBar, int orientationdata structureobject that holds thevarious valuesdata for the progress bar. @see #setModel
Class JProgressBar, boolean paintBorderThe orientation toWhetherdisplaythe progress bar is horizontal or vertical. The default isHORIZONTAL. @see #setOrientation
Whether to displayClass JProgressBar, boolean paintStringthea border around the progress bar. The default istrue. @see #setBorderPainted
Whether to textually display aClass JProgressBar, String progressStringStringstring on the progress bar. The default isfalse. Setting this totruewillcausescausea textual display of the progress todebe rendered on the progress bar. If theprogressStringisnullthe percentagedone to beof completion is displayed on the progress bar.IfOtherwise theprogressStringisnon-null it isrendered on the progress bar. @see #setStringPainted
AAn optionalStringstring that can be displayed on the progress bar. The default isnull. Setting this to a non-nullvalue does not imply that theStringstring will be displayed. @see #setString
An implementation of a radio button -- an item that can be selected or deselected and which displays its state to the user. Used with a ButtonGroup object to create a group of buttons in which only one button at a time can be selected. (Create a ButtonGroup object and use itsaddmethod to include the JRadioButton objects in the group.)Note: The ButtonGroup object is a logical grouping -- not a physical grouping. Tocreate a button panel you should still create a JPanel or similar container-object and add a javax.swing.border.Border to it to set it off from surrounding components.See How to Use Buttons Check Boxes and Radio Buttons in The Java Tutorial for further documentation.
For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JRadioButtonkey 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component which can display it's state as selected or deselected. @see ButtonGroup @see JCheckBox @version 1.64 0471 12/0603/0001 @author Jeff Dinkins
This class implements accessibility support for theJRadioButtonclass. It provides an implementation of the Java Accessibility API appropriate to radio button user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Factory method which sets theClass JRadioButton, void updateUI()ActionEventsource's properties according to values from the Action instance. The properties which are set may differ for subclasses. By default the properties which get set areTextandIconMnemonic Enabled ActionCommandToolTipText. @param a the Action from which to get the properties or null @since 1.3 @see Action @see #setAction
NotificationResetsfromtheUIFactoryUI property tothata value from theL&Fcurrent lookhas changedand feel. @see JComponent#updateUI
An implementation of a radio button menu item. AJRadioButtonMenuItemis a menu item that is part of a group of menu items in which only one item in the group can be selected. The selected item displays its selected state. Selecting it causes any other selected item to switch to the unselected state. To control the selected state of a group of radio button menu items use aButtonGroupobject.For further documentation and examples 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
JRadioButtonMenuItemkey 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component within a group of menu items which can be selected. @version 1.42 0446 12/0603/0001 @author Georges Saab @author David Karlton @see ButtonGroup
This class implements accessibility support for theJRadioButtonMenuItemclass. It provides an implementation of the Java Accessibility API appropriate toJRadioButtonMenuItemuser-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
A lightweight container used behind the scenes byJFrameJDialogJWindowJAppletandJInternalFrame. 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 containerJInternalPaneJRootPaneis also shown. All5five of these JFC/Swing containers implement theRootPaneContainerinterface 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.
The contentPane must be the parent ofToany children ofadd components to theJRootPane.Rather(other thanadding directly to a JRootPane likethethis:optional menurootPane.add(childbar);You instead addyou add the object to thecontentPaneof theJRootPanelike this:rootPane.getContentPane().add(child);The sameprinicipleprinciple 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
glassPaneif presentfills 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 theMenuBarmenuBarif 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 theJRootPaneitselfWarning: 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.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.66 0477 12/0603/0001 @author David Kloba
This class implements accessibility support for theJRootPaneclass. It provides an implementation of the Java Accessibility API appropriate to root pane user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
A custom layout manager that is responsible for the layout of layeredPane glassPane and menuBar.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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Class JRootPane, void addImpl(Component, Object, int)CreateCreates aJRootPanesetting up itsglassPaneLayeredPanelayeredPaneandcontentPane.
Overridden to enforce the position of the glass component as the zero child. @param comp the component to be enhanced @param constraints the constraints to be respected @param index the indexClass JRootPane, void addNotify()
Register ourselves with the SystemEventQueueUtils as a new root pane.
Class JRootPane, Container createContentPane()Called by the constructor methods to create the defaultClass JRootPane, Component createGlassPane()contentPane. By default this method creates a newJComponentadd sets aBorderLayoutas itsLayoutManager. @return the defaultcontentPane
Called by the constructor methods to create the defaultClass JRootPane, JLayeredPane createLayeredPane()glassPane. By default this method creates a newJComponentwith visibility set to false. @return the defaultglassPane
Called by the constructor methods to create the defaultClass JRootPane, LayoutManager createRootLayout()layeredPane. Bt default it creates a newJLayeredPane. @return the defaultlayeredPane
Called by the constructor methods to create the defaultClass JRootPane, AccessibleContext getAccessibleContext()layoutManager. @return the defaultlayoutManager.
Gets theClass JRootPane, Container getContentPane()AccessibleContextassociated with thisJRootPane. For root panes theAccessibleContexttakes the form of anAccessibleJRootPane. A newAccessibleJRootPaneinstance is created if necessary. @return anAccessibleJRootPanethat serves as theAccessibleContextof thisJRootPane
Returns the content pane -- the container that holds the components parented by the root pane. @return the Container that holds the component-contents
Class JRootPane, JButton getDefaultButton()Returns theClass JRootPane, Component getGlassPane()currentvaluedefault buttonofforthethisdefaultButtonJRootPaneproperty. @return theJButtonwhich is currently the default button @see #setDefaultButton
Returns the current glass pane for thisClass JRootPane, JMenuBar getJMenuBar()JRootPane. @return the current glass pane.@see #setGlassPane
Returns the menu bar from the layered pane. @return the JMenuBar used in the pane
Class JRootPane, JLayeredPane getLayeredPane()Class JRootPane, JMenuBar getMenuBar()GetGets the layered pane used by the root pane. The layered pane typically holds a content pane and an optionalJMenuBar. @return theJLayeredPanecurrently in use
Returns the menu bar value. @deprecated As of Swing version 1.0.3 replaced byClass JRootPane, RootPaneUI getUI()getJMenubar(). @return theJMenuBarused in the pane
Returns the L&F object that renders this component. @return LabelUI object @since 1.3
Class JRootPane, String getUIClassID()Returns a string that specifies the name of theClass JRootPane, boolean isOptimizedDrawingEnabled()lL&fF class that renders this component. @returnStringthe string "RootPaneUI" @see JComponent#getUIClassID @see UIDefaults#getUI
TheClass JRootPane, boolean isValidateRoot()GlassPaneglassPaneandContentPanecontentPanehave the same bounds which meansJRootPanedoes not tiles its children and this should return false. On the other hand theGlassPaneglassPaneis normally not visible and so this can return true if theGlassPaneglassPaneisn't visible. Therefore the return value here depends upon the visiblity of theGlassPaneglassPane. @return true if this component's children don't overlap
If a descendant of thisClass JRootPane, String paramString()JRootPanecallsrevalidatevalidate from here on down.Deferred requests to
relayoutlayout a component andit'sitsdescendants idescendents again.e.For example calls torevalidateare pushed upwards to either a()JRootPaneor aJScrollPanebecause both classes overrideisValidateRootto return true. @see JComponent#isValidateRoot @return true()
Returns a string representation of thisClass JRootPane, void removeNotify()JRootPane. 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 benull. @return a string representation of thisJRootPane.
Unregister ourselves from SystemEventQueueUtils. @see #addNotify
Class JRootPane, void setContentPane(Container)Sets the content pane -- the container that holds the components parented by the root pane. @param content theClass JRootPane, void setDefaultButton(JButton)Containerto use for component-contents @exception java.awt.IllegalComponentStateException (a runtime exception) if the content pane parameter isnull
Sets theClass JRootPane, void setGlassPane(Component)defaultButtonproperty which determines the current default button for thisJRootPane. The default button is the button which will be activated when a UI-defined activation event (typically the Enter key) occurs in theRootPaneroot pane regardless of whether or not the button has keyboard focus (unless there is another component within theRootPaneroot pane which consumes the activation event such as aJTextPane). For default activation to work the button must be an enabled descendent of theRootPaneroot pane when activation occurs. To remove a default button from thisRootPaneroot pane set this property tonull. @see JButton#isDefaultButton @param default theJButtonwhich is to be the default button @beaninfo description: The button activated by default in this root pane
Sets a specifiedClass JRootPane, void setJMenuBar(JMenuBar)Componentto be the glass pane for this root pane. The glass pane should normally be a lightweight transparent component because it will be made visible when ever the root pane needs to grab input events. For example only oneJInternalFrameis ever active when using a DefaultDesktop and any inactiveJInternalFramesJInternalFrames' glass panes are made visible so that clicking anywhere within an inactiveJInternalFramecan activate it. @param glass theComponentto use as the glass pane for thisJRootPane@exception NullPointerException if the.glassparameter isnull
Adds or changes the menu bar used in the layered pane. @param menu the JMenuBar to add
Class JRootPane, void setLayeredPane(JLayeredPane)Class JRootPane, void setMenuBar(JMenuBar)SetSets the layered pane for the root pane. The layered pane typically holds a content pane and an optionalJMenuBar. @param layered theJLayeredPaneto use.@exception java.awt.IllegalComponentStateException (a runtime exception) if the layered pane parameter isnull
Specifies the menu bar value. @deprecated As of Swing version 1.0.3 replaced byClass JRootPane, void setUI(RootPaneUI)setJMenuBar(JMenuBar menu). @param menu theJMenuBarto add.
Sets the L&F object that renders this component. @Class JRootPane, void updateUI()since 1.3 @param ui theLabelUIL&F object @see UIDefaults#getUI @beaninfo bound: true hidden: true expert: true attribute: visualUpdate true description: TheL&FUI object thatrenders thisimplements thecomponentComponent's LookAndFeel. @since 1.3
Class JRootPane, JButton defaultButtonNotificationResetsfromtheUIFactoryUI property tothata value from theL&Fcurrent lookhas changedand feel. @see JComponent#updateUI
The button that gets activated when the pane has the focus and a UI-specific action like pressing the Enter key occurs.Class JRootPane, DefaultAction defaultPressAction
As of Java 2 platform v1.3 this unusable field is no longer used. To override the default button you should replace theClass JRootPane, DefaultAction defaultReleaseActionActionin theJRootPane'sActionMap. Please refer to the key bindings specification for further details. @deprecated As of Java 2 platform v1.3. @see #defaultButton
As of Java 2 platform v1.3 this unusable field is no longer used. To override the default button you should replace theActionin theJRootPane'sActionMap. Please refer to the key bindings specification for further details. @deprecated As of Java 2 platform v1.3. @see #defaultButton
An implementation of a scrollbar. The user positions the knob in the scrollbar to determine the contents of the viewing area. The program typically adjusts the display so that the end of the scrollbar represents the end of the displayable contents or 100% of the contents. The start of the scrollbar is the beginning of the displayable contents or 0%. Thepostionposition of the knob within those bounds then translates to the corresponding percentage of the displayable contents.Typically as the position of the knob in the scrollbar changes a corresponding change is made to the position of the JViewport on the underlying view changing the contents of the JViewport.
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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see JScrollPane @beaninfo attribute: isContainer false description: A component that helps determine the visible content range of an area. @version 1.65 0472 12/0603/0001 @author David Kloba
This class implements accessibility support for theJScrollBarclass. It provides an implementation of the Java Accessibility API appropriate to scroll bar user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Creates a scrollbar with the specified orientation value extentClass JScrollBar, void addAdjustmentListener(AdjustmentListener)mimimumminimum and maximum. The "extent" is the size of the viewable area. It is also known as the "visible amount".Note: Use
setBlockIncrementto set the block increment to a size slightly smaller than the view's extent. That way when the user jumps the knob to an adjacent position one or two lines of the original contents remain in view. @exception IllegalArgumentException if orientation is not one of VERTICAL HORIZONTAL @see #setOrientation @see #setValue @see #setVisibleAmount @see #setMinimum @see #setMaximum
Adds an AdjustmentListener. Adjustment listeners are notified each time the scrollbar's model changes. Adjustment events are provided for backwardsClass JScrollBar, boolean isFocusTraversable()compatabilitycompatibility with java.awt.Scrollbar.Note that the AdjustmentEvents type property will always have a placeholder value of AdjustmentEvent.TRACK because all changes to a BoundedRangeModels value are considered equivalent. To change the value of a BoundedRangeModel one just sets its value property i.e. model.setValue(123). No information about the origin of the change e.g. it's a block decrement is provided. We don't try fabricate the origin of the change here. @param l the AdjustmentLister to add @see #removeAdjustmentListener @see BoundedRangeModel#addChangeListener
IdentifiesReturns whetheror notthiscomponentComponentcanreceivebecome the focus owner.This@returnreturnstruefalse asif thisJScrollBar'sComponentdoisnotfocusable;wantfalsetootherwiseparticipate@seein#setFocusablefocus@sincetraversalJDK1.1 @return true ifdeprecatedthis componentAs ofcan1.4receive thereplaced byfocusisFocusable().
Provides a scrollable view of a lightweight component. AJScrollPanemanages a viewport optional vertical and horizontal scroll bars and optional row and column heading viewports. You can find task-oriented documentation ofJScrollPanein How to Use Scroll Panes a section in The Java Tutorial. Note thatJScrollPanedoes not support heavyweight components.
The
![]()
JViewportprovides a window or "viewport" onto a data source -- for example a text file. That data source is the "scrollable client" (aka data model) displayed by theJViewportview. AJScrollPanebasically consists ofJScrollBars aJViewportand the wiring between them as shown in the diagram at right.In addition to the scroll bars and viewport a
JScrollPanecan have a column header and a row header. Each of these is aJViewportobject that you specify withsetRowHeaderViewandsetColumnHeaderView. The column header viewport automatically scrolls left and right tracking the left-right scrolling of the main viewport. (It never scrolls vertically however.) The row header acts in a similar fashion.By default the corners are empty. You can put a component into a corner using
setCornerin case you there is some function or decoration you would like to add to the scroll pane. The size of corner components is entirely determined by the size of the headers and scroll bars that surround them.To add a border around the main viewport you can use
setViewportBorder. (Of course you can also add a border around the whole scroll pane usingsetBorder.)For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the JScrollPane key assignments.
A common operation to want to do is to set the background color that will be used if the main viewport view is smaller than the viewport or is not opaque. This can be accomplished by setting the background color of the viewport via
scrollPane.getViewport().setBackground(). The reason for setting the color of the viewport and not the scrollpane is that by defaultJViewportis opaque which among other things means it will completely fill in its background using its background color. Therefore whenJScrollPanedraws its background the viewport will usually draw over it.By default
JScrollPaneusesScrollPaneLayoutto handle the layout of its child Components.ScrollPaneLayoutdetermines the size to make the viewport view in one of two ways:
- If the view implements
Scrollablea combination ofgetPreferredScrollableViewportSizegetScrollableTracksViewportWidthandgetScrollableTracksViewportHeightis used otherwisegetPreferredSizeis used.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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see JScrollBar @see JViewport @see ScrollPaneLayout @see Scrollable @see Component#getPreferredSize @see #setViewportView @see #setRowHeaderView @see #setColumnHeaderView @see #setCorner @see #setViewportBorder @beaninfo attribute: isContainer true attribute: containerDelegate getViewport description: A specialized container that manages a viewport optional scrollbars and headers @version 1.75 0479 09/0601/00 @author Hans Muller
This class implements accessibility support for theJScrollPaneclass. It provides an implementation of the Java Accessibility API appropriate to scroll pane user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
By defaultJScrollPanecreates scrollbars that are instances of this class.Scrollbaroverrides thegetUnitIncrementandgetBlockIncrementmethods so that if the viewport's view is aScrollablethe view is asked to compute these values. Unless the unit/block increment have been explicitly set.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see Scrollable @see JScrollPane#createVerticalScrollBar @see JScrollPane#createHorizontalScrollBar
Returns the look and feel (L&F) object that renders this component. @return the ScrollPaneUI object that renders this component @see #setUI @beaninfo bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.
Class JScrollPane, void setLayout(LayoutManager)Sets the layout manager for thisJScrollPane. This method overridessetLayoutinjava.awt.Containerto ensure that onlyLayoutManagers which are subclasses ofScrollPaneLayoutcan be used in aJScrollPane. Iflayoutis non-null this will invokesyncWithScrollPaneon it. @param layout the specified layout manager @exception ClassCastException if layout is not aScrollPaneLayout@see java.awt.Container#getLayout @see java.awt.Container#setLayout @beaninfo hidden: true
An implementationJSeparatorofprovides amenugeneralseparatorpurpose-component for implementing divider lines - most commonly used as a divider between menu items that breaks them up into logical groupings. Instead of usingJSeparatordirectly you can use theJMenuorJPopupMenuaddSeparatormethod to create and add a separator.JSeparators may also be used elsewhere in a GUI wherever a visual divider is useful.For more information and examples see How to Use Menus 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.
A futureAsreleaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A divider between menu items. @version 1.42 0448 12/0603/0001 @author Georges Saab @author Jeff Shapiro
This class implements accessibility support for theJSeparatorclass. It provides an implementation of the Java Accessibility API appropriate to separator user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Class JSeparator, void setUI(SeparatorUI)IdentifiesReturns whetheror notthiscomponentComponentcanreceivebecome the focus owner. @returntrueif thisJSeparatorComponentscannotisrecievefocusable;focusfalseotherwise @see #setFocusable @since JDK1.1 @returndeprecatedfalseAs of 1.4 replaced byisFocusable().
Sets the L&F object that renders this component. @param ui the SeparatorUI L&F object @see UIDefaults#getUI @beaninfoClass JSeparator, void updateUI()descriptionbound:The menu item's UI delegatetrueboundhidden: trueexpertattribute: visualUpdate truehiddendescription:trueThe UI object that implements the Component's LookAndFeel.
NotificationResetsfrom the UIFactory thattheL&F has changed.UICalledproperty toreplace theaUI withvalue from thelatest versioncurrentfrom thelook andUIFactorysfeel. @see JComponent#updateUI
A component that lets the user graphically select a value bysldingsliding a knob within a bounded interval. The slider can show both major tick marks and minor tick marks between them. The number of values between the tick marks is controlled withsetMajorTickSpacingandsetMinorTickSpacing.For further information and examples see How to Use Sliders 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
JSliderkey 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component that supports selecting a integer value from a range. @version 1.90 0497 12/0603/0001 @author David Kloba
This class implements accessibility support for theJSliderclass. It provides an implementation of the Java Accessibility API appropriate to slider user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Creates a horizontal slider with the range 0 to 100 and anClass JSlider, constructor JSlider(int)intitialinitial value of 50.
Creates a slider using the specified orientation with the range 0 to 100 and anClass JSlider, constructor JSlider(int, int)intitialinitial value of 50.
Creates a horizontal slider using the specified min and max with anClass JSlider, constructor JSlider(int, int, int, int)intitialinitial value equal to the average of50the min plus max.
Creates a slider with the specified orientation and the specifiedClass JSlider, Dictionary getLabelTable()mimimumminimum maximum and initial values. @exception IllegalArgumentException if orientation is not one of VERTICAL HORIZONTAL @see #setOrientation @see #setMinimum @see #setMaximum @see #setValue
Returns the dictionary of what labels to draw at which values. @return the Dictionary containing labels and where to draw them
Class JSlider, void updateLabelUIs()Class JSlider, void updateUI()CalledResetsinternally to replacethelabel UIsUIwith the latest versionsproperty to a value from theUIFactory when the UIFactory notifies us via updateUI that thecurrentL&Flookhas changedand feel. @see JComponent#updateUI
NotificationResetsfrom the UIFactory thattheL&F has changed.UICalledproperty toreplace theaUI withvalue from thelatestcurrentversion from thelookdefault UIFactoryand feel. @see JComponent#updateUI
JSplitPaneis used to divide two (and only two)Components. The twoComponents are graphically divided based on the look and feel implementation and the twoComponents can then be interactively resized by the user. Information on usingJSplitPaneis in How to Use Split Panes in The Java Tutorial.The two
Components in a split pane can be aligned left to right usingJSplitPane.HORIZONTAL_SPLITor top to bottom usingJSplitPane.VERTICAL_SPLIT. The preferred way to change the size of theComponents is to invokesetDividerLocationwherelocationis either the new x or y position depending on the orientation of theJSplitPane.To resize the
Components to their preferred sizes invokeresetToPreferredSizes.When the user is resizing the
Components the minimum size of theComponentsis used to determine the maximum/minimum position theComponents can be set to. If the minimum size of the two components is greater than the size of the split pane the divider will not allow you to resize it. To alter the minimum size of aJComponentsee JComponent#setMinimumSizeWhen the user resizes the split pane the new space is distributed between the two components based on the
resizeWeightproperty. A value of 0 the default indicates the right/bottom component gets all the space where as a value of 1 indicates the left/top component gets all the space.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JSplitPanekey 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @see #setDividerLocation @see #resetToPreferredSizes @version 1.64 0269 12/0903/01 @author Scott Violet
This class implements accessibility support for theJSplitPaneclass. It provides an implementation of the Java Accessibility API appropriate to split pane user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Adds the specified component to this split pane. IfClass JSplitPane, boolean isContinuousLayout()constraintsidentifies the left/top or right/bottom child component and a component with that identifier was previously added it will be removed and thencompwill be added in its place. Ifconstraintsis not one of the knownidentifersidentifiers the layout manager may throw anIllegalArgumentException.The possible constraints objects (Strings) are:
If the
- JSplitPane.TOP
- JSplitPane.LEFT
- JSplitPane.BOTTOM
- JSplitPane.RIGHT
constraintsobject isnullthe component is added in the first available position (left/top if open else right/bottom). @param comp the component to add @param constraints anObjectspecifying the layout constraints (position) for this component @param index an integer specifying the index in the container's list. @exception IllegalArgumentException if theconstraintsobject does not match an existing component @see java.awt.Container#addImpl(Component Object int)
Class JSplitPane, boolean isOneTouchExpandable()ReturnsGetstrue ifthechild comopnents are continuously redisplayed and layed outcontinuousLayoutduring user interventionproperty. @returntrue ifthecomponents arevaluecontinuouslyofredrawn asthedividercontinuousLayoutchangesproperty @seeposition#setContinuousLayout
Class JSplitPane, void setContinuousLayout(boolean)ReturnsGetstrue ifthepane provides a UI widget to collapse/expandoneTouchExpandablethe dividerproperty. @returntrue ifthesplit panevalue ofprovidestheoneTouchExpandableapropertycollapse/expand@seewidget#setOneTouchExpandable
SetsClass JSplitPane, void setOneTouchExpandable(boolean)whether orthe valuenotof thecontinuousLayoutproperty which must betruefor the child componentsareto be continuously redisplayed andlayedlaid out during user intervention. The default value of this property isfalse. Some look and feels might not support continuous layout; they will ignore this property. @param newContinuousLayouta booleantrueif the componentsareshould continuously be redrawn as the divider changes position @beaninfo bound: true description: Whetheror notthe child components are continuously redisplayed andlayedlaid out during user intervention. @see #isContinuousLayout
Class JSplitPane, void setUI(SplitPaneUI)DeterminesSetswhetherthe value of theoneTouchExpandableproperty which must betruefor theJSplitPaneprovidesto provide a UI widget on the divider to quickly expand/collapse the divider. The default value of this property isfalse. Some look and feels might not support one-touch expanding; they will ignore this property. @param newValueatrueboolean where true meansto specify that thetosplit pane should provide a collapse/expand widget @beaninfo bound: true description: UI widget on the divider to quickly expand/collapse the divider. @see #isOneTouchExpandable
Sets the L&F object that renders this component. @param ui the SplitPaneUI L&F object @see UIDefaults#getUI @beaninfo bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.
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.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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.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%I% %G%1.124 12/03/01 @author Dave Moore @author Philip Milne @author Amy Fowler @see SingleSelectionModel
This class implements accessibility support for theClass JTabbedPane.AccessibleJTabbedPane, AccessibleSelection getAccessibleSelection()JTabbedPaneclass. It provides an implementation of the Java Accessibility API appropriate to tabbed pane user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
GetGets theAccessibleSelectionassociated with this object. In the implementation of the Java Accessibility API for this classreturnreturns this object which is responsible for implementing theAccessibleSelectioninterface on behalf of itself. @return this object
Creates an emptyClass JTabbedPane, constructor JTabbedPane(int)TabbedPane.withThea default tab placementisofJTabbedPane.TOPand default tab layout policy ofJTabbedPane.WRAP_TAB_LAYOUT. @see #addTab
Creates an emptyClass JTabbedPane, Component add(Component)TabbedPanewith the specified tab placement of either:JTabbedPane.TOPJTabbedPane.BOTTOMJTabbedPane.LEFTorJTabbedPane.RIGHTand a default tab layout policy ofJTabbedPane.WRAP_TAB_LAYOUT. @param tabPlacement the placement for the tabs relative to the content @see #addTab
Adds aClass JTabbedPane, void addTab(String, Component)componentwith a tab title defaulting to the name of the component which is the result of callingcomponent.getName. Cover method forinsertTab. @param component the component to be displayed when this tab is clicked @return the component @see #insertTab @see #removeTabAt
Adds aClass JTabbedPane, void addTab(String, Icon, Component)componentrepresented by atitleand no icon. Cover method forinsertTab. @param title the title to be displayed in this tab @param componentThethe component to be displayed when this tab is clicked.@see #insertTab @see #removeTabAt
Adds aClass JTabbedPane, void addTab(String, Icon, Component, String)componentrepresented by atitleand/oriconeither of which can benull. Ificonis non-nulland it implementsImageIcona corresponding disabled icon will automatically be created and set on the tabbedpane. Cover method forinsertTab. @param title the title to be displayed in this tab @param icon the icon to be displayed in this tab @param component the component to be displayed when this tab is clicked @see #insertTab @see #removeTabAt
Adds aClass JTabbedPane, void fireStateChanged()componentandtiprepresented by atitleand/oriconeither of which can benull. Ificonis non-nulland it implementsImageIcona corresponding disabled icon will automatically be created and set on the tabbedpane. Cover method forinsertTab. @param title the title to be displayed in this tab @param icon the icon to be displayed in this tab @param componentThethe component to be displayed when this tab is clicked.@param tip the tooltip to be displayed for this tab @see #insertTab @see #removeTabAt
Class JTabbedPane, Color getBackgroundAt(int)SendSends aChangeEventwhose source is this tabbedpane to each listener. This method method is called each time aChangeEventis received from the model. @see #addChangeListener @see EventListenerList
Returns the tab background color atClass JTabbedPane, Rectangle getBoundsAt(int)index. @param index the index of the item being queried @return theColorof the tab background atindex@exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index <0 || index >= tab count) @see #setBackgroundAt
Returns the tab bounds atClass JTabbedPane, Component getComponentAt(int)index. If the tab at this index is not currently visible in the UI then returnsnull. If there is no UI set on thistabbedpanethen returnsnull. @param index the index to be queried @return aRectanglecontaining the tab bounds atindexornullif tab atindexis not currently visible in the UI or if there is no UI set on thistabbedpane@exception IndexOutOfBoundsException if index is out of range (index < 0 || index >= tab count)
Returns the component atClass JTabbedPane, Icon getDisabledIconAt(int)index. @param index the index of the item being queried @return theComponentatindex@exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index <0 || index >= tab count) @see #setComponentAt
Returns the tab disabled icon atClass JTabbedPane, Color getForegroundAt(int)index. @param index the index of the item being queried @return the icon atindex@exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index <0 || index >= tab count) @see #setDisabledIconAt
Returns the tab foreground color atClass JTabbedPane, Icon getIconAt(int)index. @param index the index of the item being queried @return theColorof the tab foreground atindex@exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index <0 || index >= tab count) @see #setForegroundAt
Returns the tab icon atClass JTabbedPane, int getTabRunCount()index. @param index the index of the item being queried @return the icon atindex@exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index <0 || index >= tab count) @see #setIconAt * Ificonis non-null and it implementsImageIcona corresponding disabled icon will automatically be created and set on the tabbedpane.
Returns the number of tab runs currently used to display the tabs. @return an integer giving the number of rows if theClass JTabbedPane, String getTitleAt(int)tabPlacementisTOPorBOTTOMand the number of columns iftabPlacementisLEFTorRIGHTor 0 if there is no UI set on thistabbedpane
Returns the tab title atClass JTabbedPane, String getToolTipText(MouseEvent)index. @param index the index of the item being queried @return the title atindex@exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index <0 || index >= tab count) @see #setTitleAt
Returns the tooltip text for the component determined by the mouse event location. @param event theClass JTabbedPane, String getToolTipTextAt(int)MouseEventthat tells where the cursor is lingering @return theStringcontaining the tooltip text@exception IllegalArgumentException if index is out of bounds
Returns the tab tooltip text atClass JTabbedPane, TabbedPaneUI getUI()index. @param index the index of the item being queried @return a string containing the tool tip text atindex@exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index <0 || index >= tab count) @see #setToolTipTextAt
Returns the UI object which implements the L&F for this component. @return a TabbedPaneUI object @see #setUI
Class JTabbedPane, void insertTab(String, Icon, Component, String, int)Inserts aClass JTabbedPane, boolean isEnabledAt(int)componentatindexrepresented by atitleand/oriconeither of which may benull. Ificonis non-nulland it implementsImageIcona corresponding disabled icon will automatically be created and set on the tabbedpane. Uses java.util.Vector internally seeinsertElementAtfor details of insertion conventions. @param title the title to be displayed in this tab @param icon the icon to be displayed in this tab @param component The component to be displayed when this tab is clicked. @param tip the tooltip to be displayed for this tab @param index the position to insert this new tab @see #addTab @see #removeTabAt
Returns whether or not the tab atClass JTabbedPane, void remove(Component)indexis currently enabled. @param index the index of the item being queried @return true if the tab atindexis enabled; false otherwise @exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index <0 || index >= tab count) @see #setEnabledAt
Removes theClass JTabbedPane, void remove(int)tab whichspecifiedcorrespondsComponenttofrom thespecified componentJTabbedPane. @param component the component to remove from the tabbedpane @exception NullPointerException ifcomponentis null. @see #addTab @see #removeTabAt
Removes the tab and component which corresponds to the specified index. @param index the index of the component to remove from the tabbedpane @exception IndexOutOfBoundsException if index is out of range (index <0 || index >= tab count) @see #addTab @see #removeTabAt
Class JTabbedPane, void removeChangeListener(ChangeListener)Removes aClass JTabbedPane, void removeTabAt(int)ChangeListenerfrom this tabbedpane. @param l theChangeListenerto remove @see #fireStateChanged @see #addChangeListener
Removes the tab atClass JTabbedPane, void setBackgroundAt(int, Color)index. After the component associated withindexis removed its visibility is reset to true to ensure it will be visible if added to other containers. @param index the index of the tab to be removed @exception IndexOutOfBoundsException if index is out of range (index <0 || index >= tab count) @see #addTab @see #insertTab
Sets the background color atClass JTabbedPane, void setComponentAt(int, Component)indextobackgroundwhich can benullin which case the tab's background color will default to the background color of thetabbedpane. An internal exception is raised if there is no tab at that index. @param index the tab index where the background should be set @param background the color to be displayed in the tab's background @exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index < 0 || index >= tab count) @see #getBackgroundAt @beaninfo preferred: true attribute: visualUpdate true description: The background color at the specified tab index.
Sets the component atClass JTabbedPane, void setDisabledIconAt(int, Icon)indextocomponent. An internal exception is raised if there is no tab at that index. @param index the tab index where this component is being placed @param component the component for the tab @exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index < 0 || index >= tab count) @see #getComponentAt @beaninfo attribute: visualUpdate true description: The component at the specified tab index.
Sets the disabled icon atClass JTabbedPane, void setEnabledAt(int, boolean)indextoiconwhich can benull. An internal exception is raised if there is no tab at that index. @param index the tab index where the disabled icon should be set @param icon the icon to be displayed in the tab when disabled @exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index < 0 || index >= tab count) @see #getDisabledIconAt @beaninfo preferred: true attribute: visualUpdate true description: The disabled icon at the specified tab index.
Sets whether or not the tab atClass JTabbedPane, void setForegroundAt(int, Color)indexis enabled. An internal exception is raised if there is no tab at that index. @param index the tab index which should be enabled/disabled @param enabled whether or not the tab should be enabled @exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index < 0 || index >= tab count) @see #isEnabledAt
Sets the foreground color atClass JTabbedPane, void setIconAt(int, Icon)indextoforegroundwhich can benullin which case the tab's foreground color will default to the foreground color of thistabbedpane. An internal exception is raised if there is no tab at that index. @param index the tab index where the foreground should be set @param foreground the color to be displayed as the tab's foreground @exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index < 0 || index >= tab count) @see #getForegroundAt @beaninfo preferred: true attribute: visualUpdate true description: The foreground color at the specified tab index.
Sets the icon atClass JTabbedPane, void setSelectedIndex(int)indextoiconwhich can benull. Does not set disabled icon aticonTo set disabled icon usesetDisableIconAt(). An internal exception is raised if there is no tab at that index. @param index the tab index where the icon should be set @param icon the icon to be displayed in the tab @exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index <0 || index >= tab count) @see #setDisabledIconAt @see #getIconAt @beaninfo preferred: true attribute: visualUpdate true description: The icon at the specified tab index.
Sets the selected index for this tabbedpane. The index must be a valid tab index or -1 which indicates that no tab should be selected (can also be used when there are no tabs in the tabbedpane). If a -1 value is specified when the tabbedpane contains one or more tabs then the results will be implementation defined. @param index the index to be selected @exceptionClass JTabbedPane, void setTabPlacement(int)IllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index <-1 || index >= tab count) @see #getSelectedIndex @see SingleSelectionModel#setSelectedIndex @beaninfo preferred: true description: The tabbedpane's selected tab index.
Sets the tab placement for this tabbedpane. Possible values are:Class JTabbedPane, void setTitleAt(int, String)The default value if not set is
SwingConstantsJTabbedPane.TOPSwingConstantsJTabbedPane.BOTTOMSwingConstantsJTabbedPane.LEFTSwingConstantsJTabbedPane.RIGHTSwingConstants.TOP. @param tabPlacement the placement for the tabs relative to the content @exception IllegalArgumentException if tab placement value isn't one of the above valid values @beaninfo preferred: true bound: true attribute: visualUpdate true enum: TOP JTabbedPane.TOP LEFT JTabbedPane.LEFT BOTTOM JTabbedPane.BOTTOM RIGHT JTabbedPane.RIGHT description: The tabbedpane's tab placement.
Sets the title atClass JTabbedPane, void setToolTipTextAt(int, String)indextotitlewhich can benull. An internal exception is raised if there is no tab at that index. @param index the tab index where the title should be set @param title the title to be displayed in the tab @exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index < 0 || index >= tab count) @see #getTitleAt @beaninfo preferred: true attribute: visualUpdate true description: The title at the specified tab index.
Sets the tooltip text atClass JTabbedPane, void updateUI()indextotoolTipTextwhich can benull. An internal exception is raised if there is no tab at that index. @param index the tab index where the tooltip text should be set @param toolTipText the tooltip text to be displayed for the tab @exceptionIllegalArgumentExceptionIndexOutOfBoundsException if index is out ofboundsrange (index < 0 || index >= tab count) @see #getToolTipTextAt @beaninfo preferred: true description: The tooltip text at the specified tab index.
Class JTabbedPane, ChangeListener changeListenerNotificationResetsfrom the UIManager thattheL&F has changed.UICalledproperty toreplace theaUI withvalue from thelatestcurrentversion from thelookdefaultandUIFactoryfeel. @see JComponent#updateUI
The changeListener is the listener we add to the model.
TheJTableisa user-interface componentusedthat presents data in ato display and edit regular two-dimensionaltabletablesformatof 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);
BecauseNote that if you wish to use aJTablein 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
theJTableit isnow much easierworth paying close attention toset upthe datawithstructures thatcustom modelswill represent the table's data. TheDefaultTableModelisless useful than it was ina model implementation that uses apreviousVectorreleases.ofInsteadVectors ofObjects to store the cell values. As well as copying the datainfrom an application into theDefaultTableModelweitrecommend wrappingis alsoitpossible to wrap the data in the methods of theTableModelinterfaceand passingso that therealdata can be passed to theJTabledirectly as in the example above. Thistechnique is nearly as concise as using aoften results in more efficient applications because theDefaultTableModelmodeland starting this way has a number of advantages overis free to choose the internal representation that best suits thelonger termdata.InAparticular:goodit is a scalable technique can more easily handlerule of thumb for deciding whether to use thedynamicAbstractTableModeloreditable tables and oftentheresultsDefaultTableModelin much more efficientis to use theapplicationsAbstractTableModelbecauseas themodelbaseis free to choose the internalclass for creating subclasses and therepresentationDefaultTableModelthat best suits the datawhen subclassing is not required.The "
TableTableExample" directory in theexamples/demo area of the source distribution gives a number of complete examples ofJTableusage 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.For example overriding AbstractTableModel's getColumnClass method to return a value of ImageIcon.class for a given column allows icons to be displayed while returning a value of Number.class allows digits to be right-justified in the column.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 retrieveand displaytheappropriatevalues from the model.IfduringgetTableHeader()painting.setReorderingAllowed(boolean) is used toenable column reorderingBy 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.
The general rule for the JTable API and the APIs of all its associated classes including the column model and both the row and column selection models is: methods using integer indices for rows and columns always use the coordinate system of the view. There are three exceptions to this rule: All references to rows and columns in the TableModel interface are in the coordinate system of the model. The index modelIndex in the TableColumn constructors refers to the index of the column in the model not the view. All constructors for the TableModelEvent which describes changes that have taken place in a table model use the coordinate system of the model. The TableColumn provides a slot for holding an identifier or "tag" for each column and the JTable and TableColumnModel both support getColumn(Object id) conveniences for locating columns by their identifier. If no identifier is explicitly set the TableColumn returns its header value (the name of the column) as a default. A different identifier which can be of any type can be set using the TableColumn's setIdentifier method. All of the JTable's functions operate correctly regardless of the type and uniqueness of these identifiers. The convertColumnIndexToView and convertColumnIndexToModel methods have been provided to convert between the two coordinate systems but they are rarely needed during normal use.As for allJComponentclasses 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component which displays data in a two dimensional grid. @version 1.168 02197 12/0903/01 @author Philip Milne
This class implements accessibility support for theJTableclass. It provides an implementation of the Java Accessibility API appropriate to table user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Constructs an AccessibleJTableHeaderEntry.
Class JTable.AccessibleJTable.AccessibleJTableCell, void addPropertyChangeListener(PropertyChangeListener)Class JTable.AccessibleJTable.AccessibleJTableCell, boolean contains(Point)AddAdds aPropertyChangeListenerto the listener list. The listener is registered for all properties. @param listenerThethePropertyChangeListenerto be added
Checks whether the specified point is within this object's bounds where the point's x and y coordinates are defined to be relative to the coordinate system of the object. @param p theClass JTable.AccessibleJTable.AccessibleJTableCell, AccessibleAction getAccessibleAction()Pointrelative to the coordinate system of the object @return true if object containsPoint; otherwise false
Gets theClass JTable.AccessibleJTable.AccessibleJTableCell, Accessible getAccessibleChild(int)AccessibleActionassociated with this object if one exists. Otherwise returnsnull. @return theAccessibleActionornull
Class JTable.AccessibleJTable.AccessibleJTableCell, int getAccessibleChildrenCount()ReturnReturns the specifiedAccessiblechild of the object. @param i zero-based index of child @return theAccessiblechild of the object
Returns the number of accessible children in the object. @return the number of accessible children in the objectClass JTable.AccessibleJTable.AccessibleJTableCell, AccessibleComponent getAccessibleComponent().
Gets theClass JTable.AccessibleJTable.AccessibleJTableCell, AccessibleContext getAccessibleContext()AccessibleComponentassociated with this object if one exists. Otherwise returnsnull. @return theAccessibleComponentornull
Gets theClass JTable.AccessibleJTable.AccessibleJTableCell, String getAccessibleDescription()AccessibleContextassociated with this component. In the implementation of the Java Accessibility API for this class return this object which is its ownAccessibleContext. @return this object
Gets the accessible description of this object. @return the localized description of the object; null if this object does not have a description
Class JTable.AccessibleJTable.AccessibleJTableCell, int getAccessibleIndexInParent()Gets the index of this object in its accessible parent. @return the index of this object in its parent; -1 if this object does not have an accessible parentClass JTable.AccessibleJTable.AccessibleJTableCell, String getAccessibleName().@see #getAccessibleParent
Gets the accessible name of this object. @return the localized name of the object; null if this object does not have a name
Class JTable.AccessibleJTable.AccessibleJTableCell, Accessible getAccessibleParent()Gets theClass JTable.AccessibleJTable.AccessibleJTableCell, AccessibleRole getAccessibleRole()Accessibleparent of this object. @return the Accessible parent of this object;nullif this object does not have anAccessibleparent
Gets the role of this object. @return an instance of AccessibleRole describing the role of the object @see AccessibleRole
Class JTable.AccessibleJTable.AccessibleJTableCell, AccessibleSelection getAccessibleSelection()Gets theClass JTable.AccessibleJTable.AccessibleJTableCell, AccessibleStateSet getAccessibleStateSet()AccessibleSelectionassociated with this object if one exists. Otherwise returnsnull. @return theAccessibleSelectionornull
Gets the state set of this object. @return an instance of AccessibleStateSet containing the current state set of the object @see AccessibleState
Class JTable.AccessibleJTable.AccessibleJTableCell, AccessibleText getAccessibleText()Gets theClass JTable.AccessibleJTable.AccessibleJTableCell, AccessibleValue getAccessibleValue()AccessibleTextassociated with this object if one exists. Otherwise returnsnull. @return theAccessibleTextornull
Gets theClass JTable.AccessibleJTable.AccessibleJTableCell, Color getBackground()AccessibleValueassociated with this object if one exists. Otherwise returnsnull. @return theAccessibleValueornull
Gets the background color of this object. @return the background color if supported of the object; otherwise null.
Class JTable.AccessibleJTable.AccessibleJTableCell, Cursor getCursor()Gets theClass JTable.AccessibleJTable.AccessibleJTableCell, Font getFont()Cursorof this object. @return theCursorif supported of the object; otherwisenull
Gets theClass JTable.AccessibleJTable.AccessibleJTableCell, FontMetrics getFontMetrics(Font)Fontof this object. @return theFontif supported for the object; otherwisenull
Gets theClass JTable.AccessibleJTable.AccessibleJTableCell, Color getForeground()FontMetricsof this object. @param f theFont@return theFontMetricsobject if supportedthe object; otherwisenull@see #getFont
Gets the foreground color of this object. @return the foreground color if supported of the object; otherwise null
Class JTable.AccessibleJTable.AccessibleJTableCell, Locale getLocale()Gets the locale of the component. If the component does not have a locale then the locale of its parent is returned. @return this component's locale; if this component does not have a locale the locale of its parent is returned @exception IllegalComponentStateException if the Component does not have its own locale and has not yet been added to a containment hierarchy such that the locale can be determined from the containing parent @see #setLocale
Class JTable.AccessibleJTable.AccessibleJTableCell, Point getLocation()Gets the location of the object relative to the parent in the form of a point specifying the object's top-left corner in the screen's coordinate space. @return an instance ofClass JTable.AccessibleJTable.AccessibleJTableCell, Point getLocationOnScreen()Pointrepresenting the top-left corner of the object's bounds in the coordinate space of the screen;nullif this object or its parent are not on the screen
Returns the location of the object on the screen. @return location of object on screen -- can be null if this object is not on the screen
Class JTable.AccessibleJTable.AccessibleJTableCell, boolean isVisible()Determines if this object is visible. Note: this means that the object intends to be visible; however it may not in fact be showing on the screen because one of the objects that this object is contained by is not visible. To determine if an object is showing on the screen use isShowing(). @return true if object is visible; otherwise false
Class JTable.AccessibleJTable.AccessibleJTableCell, void removePropertyChangeListener(PropertyChangeListener)Class JTable.AccessibleJTable.AccessibleJTableCell, void setAccessibleName(String)RemoveRemoves aPropertyChangeListenerfrom the listener list. This removes aPropertyChangeListenerthat was registered for all properties. @param listenerThethePropertyChangeListenerto be removed
Sets the localized accessible name of this object. @param s the new localized name of the objectClass JTable.AccessibleJTable.AccessibleJTableCell, void setBackground(Color).
Sets the background color of this object. @param c the new Color for the background
Class JTable.AccessibleJTable.AccessibleJTableCell, void setCursor(Cursor)Sets theClass JTable.AccessibleJTable.AccessibleJTableCell, void setFont(Font)Cursorof this object. @param c the newCursorfor the object
Sets theClass JTable.AccessibleJTable.AccessibleJTableCell, void setForeground(Color)Fontof this object. @param f the newFontfor the object
Sets the foreground color of this object. @param c the new Color for the foreground
Adds the specifiedClass JTable.AccessibleJTable, Accessible getAccessibleAt(Point)Accessiblechild of the object to the object's selection. If the object supports multiple selections the specified child is added to any existing selection otherwise it replaces any existing selection in the object. If the specified child is already selected this method has no effect.This method only works on
JTablesJTables which have individual cell selection enabled. @param i the zero-based index of the child @see AccessibleContext#getAccessibleChild
Returns theClass JTable.AccessibleJTable, Accessible getAccessibleChild(int)Accessiblechild if one exists contained at the local coordinatePoint. @param p the point defining the top-left corner of theAccessiblegiven in the coordinate space of the object's parent.@return theAccessibleif it exists at the specified location; elsenull
Class JTable.AccessibleJTable, int getAccessibleChildrenCount()ReturnReturns the nthAccessiblechild of the object. @param i zero-based index of child @return the nth Accessible child of the object
Returns the number of accessible children in the object. If all of the children of this object implementClass JTable.AccessibleJTable, Accessible getAccessibleColumnDescription(int)Accessiblethanthen this method should return the number of children of this object. @return the number of accessible children in the object.
Class JTable.AccessibleJTable, int getAccessibleColumnExtentAt(int, int)ReturnReturns the description of the specified column in the table. @param c zero-based column of the table @return the description of the column
Returns the number of columns occupied by theClass JTable.AccessibleJTable, AccessibleTable getAccessibleColumnHeader()Accessibleat a given (row column). @return the number of columns occupied by theAccessibleat a specified row and column in the table.
Class JTable.AccessibleJTable, int getAccessibleIndexAt(int, int)ReturnReturns the column headers as anAccessibleTable. @return anAccessibleTablerepresenting the column headers
Returns the index at a given (row column) in the table. @param r zero-based row of the table @param c zero-based column of the table @return the index into the tableClass JTable.AccessibleJTable, Accessible getAccessibleRowDescription(int)
Class JTable.AccessibleJTable, int getAccessibleRowExtentAt(int, int)ReturnReturns the description of the specified row in the table. @param r zero-based row of the table @return the description of the row
Returns the number of rows occupied by theClass JTable.AccessibleJTable, AccessibleTable getAccessibleRowHeader()Accessibleat a specified row and column in the table. @return the number of rows occupied by theAccessibleat a specified row and column in the table.
Class JTable.AccessibleJTable, Accessible getAccessibleSelection(int)ReturnReturns the row headers as anAccessibleTable. @return anAccessibleTablerepresenting the row headers
Returns anClass JTable.AccessibleJTable, int getAccessibleSelectionCount()Accessiblerepresenting the specified selected child in the object. If there isn't a selection or there are fewer children selected than the integer passed in the return value will benull.Note that the index represents the i-th selected child which is different from the i-th child. @param i the zero-based index of selected children @return the i-th selected child @see #getAccessibleSelectionCount
Returns the number ofClass JTable.AccessibleJTable, AccessibleTable getAccessibleTable()Accessiblechildren currently selected. If no children are selected the return value will be 0. @return the number of items currently selected.
Class JTable.AccessibleJTable, boolean isAccessibleChildSelected(int)GetGets theAccessibleTableassociated with this object. In the implementation of the Java Accessibility API for this class return this object which is responsible for implementing theAccessibleTableAccessibleTablesinterface on behalf of itself. @return this object
Determines if the current child of this object is selected. @Class JTable.AccessibleJTable, boolean isAccessibleColumnSelected(int)return true if the current child of this object is selected @param i the zero-based index of the child in thisAccessibleobject.@return true if the current child of this object is selected @see AccessibleContext#getAccessibleChild
Returns a boolean value indicating whether the specified column is selected. @param r zero-based column of the table @return the boolean value true if the specified column is selectedClass JTable.AccessibleJTable, boolean isAccessibleRowSelected(int). Otherwise; otherwise false.
Returns a boolean value indicating whether the specified row is selected. @param r zero-based row of the table @return the boolean value true if the specified row is selectedClass JTable.AccessibleJTable, boolean isAccessibleSelected(int, int). Otherwise; otherwise false.
Returns a boolean value indicating whether the accessible at a given (row column) is selected. @param r zero-based row of the table @param c zero-based column of the table @return the boolean value true if the accessible at (row column) is selectedClass JTable.AccessibleJTable, void removeAccessibleSelection(int). Otherwise; otherwise the boolean value false
Removes the specified child of the object from the object's selection. If the specified item isn't currently selected this method has no effect.Class JTable.AccessibleJTable, void selectAllAccessibleSelection()This method only works on
JTableswhich have individual cell selection enabled. @param i the zero-based index of the child @see AccessibleContext#getAccessibleChild
Causes every child of the object to be selected but only if the JTable supports multiple selections and if individual cell selection is enabled.
Class JTable.AccessibleJTable, void setAccessibleColumnHeader(AccessibleTable)Class JTable.AccessibleJTable, void setAccessibleRowHeader(AccessibleTable)ReturnReturns the column headers as anAccessibleTable. @return anAccessibleTablerepresenting the column headers
ReturnReturns the row headers as anAccessibleTable. @return anAccessibleTablerepresenting the row headers
Constructs aClass JTable, void doLayout()JTableto display the values in theVectorofVectorsrowDatawith column namescolumnNames. TheVectorscontained inrowDatashould contain the values for that row. In other words the value of the cell at row 1 column 5 can be obtained with the following code:
((Vector)rowData.elementAt(1)).elementAt(5);
Each row must contain a value for each column or an exception will be raised.@param rowData the data for the new table @param columnNames names of each column
Causes this table to lay out its rows and columns. Overridden so that columns can be resized to accomodate a change in the size of a containing parent. Resizes one or more of the columns in the table so that the total width of all of thisClass JTable, boolean editCellAt(int, int)JTable's columns is equal to the width of the table.Before the layout begins the method gets the
resizingColumnof thetableHeader. When the method is called as a result of the resizing of an enclosing window theresizingColumnisnull. This means that resizing has taken place "outside" theJTableand the change - or "delta" - should be distributed to all of the columns regardless of thisJTable's automatic resize mode.If the
resizingColumnis notnullit is one of the columns in the table that has changed size rather than the table itself. In this case the auto-resize modes govern the way the extra (or deficit) space is distributed amongst the available columns.The modes are:
- AUTO_RESIZE_OFF: Don't automatically adjust the column's widths at all. Use a horizontal scrollbar to accomodate the columns when their sum exceeds the width of the
Viewport. If theJTableis not enclosed in aJScrollPanethis may leave parts of the table invisible.- AUTO_RESIZE_NEXT_COLUMN: Use just the column after the resizing column. This results in the "boundary" or divider between adjacent cells being independently adjustable.
- AUTO_RESIZE_SUBSEQUENT_COLUMNS: Use all columns after the one being adjusted to absorb the changes. This is the default behavior.
- AUTO_RESIZE_LAST_COLUMN: Automatically adjust the size of the last column only. If the bounds of the last column prevent the desired size from being allocated set the width of the last column to the appropriate limit and make no further adjustments.
- AUTO_RESIZE_ALL_COLUMNS: Spread the delta amongst all the columns in the
JTableincluding the one that is being adjusted.
Note: When aJTablemakes adjustments to the widths of the columns it respects their minimum and maximum values absolutely. It is therefore possible that even after this method is called the total width of the columns is still not equal to the width of the table. When this happens theJTabledoes not put itself in AUTO_RESIZE_OFF mode to bring up a scroll bar or break other commitments of its current auto-resize mode -- instead it allows its bounds to be set larger (or smaller) than the total of the column minimum or maximum meaning either that there will not be enough room to display all of the columns or that the columns will not fill theJTable's bounds. These respectively result in the clipping of some columns or an area being painted in theJTable's background color during painting.The mechanism for distributing the delta amongst the available columns is provided in a private method in the
JTableclass:adjustSizes(long targetSize final Resizable3 r boolean inverse)an explanation of which is provided in the following section.Resizable3is a private interface that allows any data structure containing a collection of elements with a size preferred size maximum size and minimum size to have its elements manipulated by the algorithm.
Distributing the delta
Overview
Call "DELTA" the difference between the target size and the sum of the preferred sizes of the elements in r. The individual sizes are calculated by taking the original preferred sizes and adding a share of the DELTA - that share being based on how far each preferred size is from its limiting bound (minimum or maximum).
Definition
Call the individual constraints min[i] max[i] and pref[i].
Call their respective sums: MIN MAX and PREF.
Each new size will be calculated using:
size[i] = pref[i] + delta[i]where each individual delta[i] is calculated according to:If (DELTA <0) we are in shrink mode where:
DELTA delta[i] = ------------ * (pref[i] - min[i]) (PREF - MIN)If (DELTA > 0) we are in expand mode where:
DELTA delta[i] = ------------ * (max[i] - pref[i]) (MAX - PREF)The overall effect is that the total size moves that same percentage k towards the total minimum or maximum and that percentage guarantees accomodation of the required space DELTA.
Details
Naive evaluation of the formulae presented here would be subject to the aggregated rounding errors caused by doing this operation in finite precision (using ints). To deal with this the multiplying factor above is constantly recalculated and this takes account of the rounding errors in the previous iterations. The result is an algorithm that produces a set of integers whose values exactly sum to the supplied
targetSizeand does so by spreading the rounding errors evenly over the given elements.When the MAX and MIN bounds are hit
When
targetSizeis outside the [MIN MAX] range the algorithm sets all sizes to their appropriate limiting value (maximum or minimum).
Programmatically starts editing the cell atClass JTable, boolean editCellAt(int, int, EventObject)rowandcolumnif the cell is editable. Note that this is a convenience method foreditCellAt(int int null). @param row the row to be edited @param column the column to be edited @exception IllegalArgumentExceptionIfifroworcolumnis not in the valid range @return false if for any reason the cell cannot be edited
Programmatically starts editing the cell atClass JTable, int getAutoResizeMode()rowandcolumnif the cell is editable. To prevent theJTablefrom editing a particular table column or cell value return false from theisCellEditablemethod in theTableModelinterface. @param row the row to be edited @param column the column to be edited @param e event to pass intoshouldSelectCell; note that as of Java 2 platform v1.2 the call toshouldSelectCellis no longer made @exception IllegalArgumentExceptionIfifroworcolumnis not in the valid range @return false if for any reason the cell cannot be edited
Returns the auto resize mode of the table. The default mode is AUTO_RESIZE_SUBSEQUENT_COLUMNS. @return the autoResizeMode of the table @see #setAutoResizeMode @see #Class JTable, Rectangle getCellRect(int, int, boolean)sizeColumnsToFit(int)doLayout
Returns a rectangle for the cell that lies at the intersection ofClass JTable, Color getGridColor()rowandcolumn. 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
theyandheightvalues 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
calulationscalculations that use this method to calculate results along oneaxixaxis will not fail because of anomalies in calculations along the other axis. When the cell is not valid theincludeSpacingparameter is ignored. @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
Returns the color used to draw grid lines. The default color isClass JTable, boolean getScrollableTracksViewportWidth()Color.graylook and feel dependent. @return the color used to draw grid lines @see #setGridColor
Returns false ifClass JTable, boolean isFocusTraversable()autoResizeModeis set toindicateAUTO_RESIZE_OFFwhich indicates that the width of the viewport does not determine the width of the table. Otherwise returns true. @return false ifautoResizeModeis set toAUTO_RESIZE_OFFotherwise returns true @see Scrollable#getScrollableTracksViewportWidth
Class JTable, boolean isManagingFocus()We overrideReturns whether thismethod whose implementation inJComponentComponentreturnscanfalse to return truebecome the focus owner.This@returnindicatestruethat theif thisisJTableComponentafocusable;falsecomponentotherwisethat@seeshould#setFocusablebe@sincepartJDK1.1of@deprecatedaAs(tabbing)offocus1.4cyclereplaced bydefaultisFocusable().@return true
Class JTable, Component prepareRenderer(TableCellRenderer, int, int)WeChangesoverridethismethod whose implementation inJComponent's focusreturns falsetraversal keys toreturnCTRL+TAB andtrueCTRL+SHIFT+TAB.ThisAlso preventsallowsSortingFocusTraversalPolicyusfromtoconsidering descendants of this JComponentgivewhen computing aspecial meaningfocus traversaltocycle.TAB@seeandjava.awt.Component#setFocusTraversalKeysSHIFT-TAB@see SortingFocusTraversalPolicy @deprecated Asinofthe1.4 replaced byJTableComponent.setFocusTraversalKeys(int@returnSet)trueandContainer.setFocusCycleRoot(boolean).
Prepares the renderer by querying the data model for the value and selection state of the cell atClass JTable, void setAutoResizeMode(int)rowcolumn. Returns the component (may be aComponentor aJComponent) under the event location.Note: Throughout the table package the internal implementations always use this method to prepare renderers so that this default behavior can be safely overridden by a subclass. @param renderer the
TableCellRendererto prepare @param row the row of the cell to render where 0 is the first row @param column the column of the cell to render where 0 is the first column @return theComponentunder the event location
Sets the table's auto resize mode when the table is resized. @param mode One of 5 legal values: AUTO_RESIZE_OFF AUTO_RESIZE_NEXT_COLUMN AUTO_RESIZE_SUBSEQUENT_COLUMNS AUTO_RESIZE_LAST_COLUMN AUTO_RESIZE_ALL_COLUMNS @see #getAutoResizeMode @see #Class JTable, void setCellSelectionEnabled(boolean)sizeColumnsToFit(int)doLayout @beaninfo bound: true description: Whether the columns should adjust themselves automatically. enum: AUTO_RESIZE_OFF JTable.AUTO_RESIZE_OFF AUTO_RESIZE_NEXT_COLUMN JTable.AUTO_RESIZE_NEXT_COLUMN AUTO_RESIZE_SUBSEQUENT_COLUMNS JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS AUTO_RESIZE_LAST_COLUMN JTable.AUTO_RESIZE_LAST_COLUMN AUTO_RESIZE_ALL_COLUMNS JTable.AUTO_RESIZE_ALL_COLUMNS
Sets whether this table allows both a column selection and a row selection to exist simultaneously. When set the table treats the intersection of the row and column selection models as the selected cells. OverrideClass JTable, void setColumnSelectionAllowed(boolean)isCellSelectedto change this default behavior. This method is equivalent to setting both therowSelectionAllowedproperty andcolumnSelectionAllowedproperty of thecolumnModelto the supplied value. @param cellSelectionEnabled true if simultaneous row and column selection is allowed @see #getCellSelectionEnabled @see #isCellSelected @beaninfo bound: true attribute: visualUpdate true description: Select a rectangular region of cells rather than rows or columns.
Sets whether the columns in this model can be selected. @param columnSelectionAllowed true if this model will allow column selection @see #getColumnSelectionAllowed @beaninfo bound: true attribute: visualUpdate true description: If true an entire column is selected for each selected cell.Class JTable, void setGridColor(Color)
Sets the color used to draw grid lines toClass JTable, void setRowHeight(int)gridColorand redisplays. The default color isColor.graylook and feel dependent. @param gridColor the new color of the grid lines @exception IllegalArgumentException ifgridColorisnull@see #getGridColor @beaninfo bound: true description: The grid color.
Sets the height in pixels of all cells toClass JTable, void setRowSelectionAllowed(boolean)rowHeightrevalidates and repaints. The height of the cellsin this rowwill be equal to the row height minus the row margin. @param rowHeight new row height @exception IllegalArgumentException ifrowHeightis less than 1 @see #getRowHeight @beaninfo bound: true description: The height of the specified row.
Sets whether the rows in this model can be selected. @param rowSelectionAllowed true if this model will allow row selection @see #getRowSelectionAllowed @beaninfo bound: true attribute: visualUpdate true description: If true an entire row is selected for each selected cell.Class JTable, void setUI(TableUI)
Sets the L&F object that renders this component and repaints. @param ui the TableUI L&F object @see UIDefaults#getUI @beaninfo bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.Class JTable, void sizeColumnsToFit(boolean)
Sizes the table columns to fit the available space. @deprecated As of Swing version 1.0.3 replaced byClass JTable, void sizeColumnsToFit(int). @see #sizeColumnsToFitdoLayout(int)sizeColumnsToFit(int)doLayout
Class JTable, void tableChanged(TableModelEvent)ResizesObsoleteone or more of the columns in the table so that the total width of all of this JTable's columns is equal to the width of the table. When doLayout is called on this JTable oftenasa result of the resizingofan enclosingJavawindow2this method is called with resizingColumn set toplatform-1v1.This means that resizing has taken place "outside" the JTable and the change - or "delta" - should be distributed to all of the columns regardless of this JTable's automatic resize mode4.IfPlease use theresizingColumn is not -1 it is one of the columns in the table that has changed size rather than the table itself. In this case the auto-resize modes govern the way the extradoLayout(or deficit)space is distributed amongst the available columns. The modes are: AUTO_RESIZE_OFF: Don't automatically adjust the column's widths at all. Use a horizontal scrollbar to accomodate the columns when their sum exceeds the width of the Viewport. If the JTable is not enclosed in a JScrollPane this may leave parts of the table invisible. AUTO_RESIZE_NEXT_COLUMN: Use just the column after the resizing column. This results in the "boundary" or divider between adjacent cells being independently adjustable. AUTO_RESIZE_SUBSEQUENT_COLUMNS: Use all columns after the one being adjusted to absorb the changes. This is the default behavior. AUTO_RESIZE_LAST_COLUMN: Automatically adjust the size of the last column only. If the bounds of the last column prevent the desired size from being allocated set the width of the last column to the appropriate limit and make no further adjustments. AUTO_RESIZE_ALL_COLUMNS: Spread the delta amongst all the columns in the JTable including the one that is being adjusted. Note: When a JTablemakes adjustments to the widths of the columns it respects their minimum and maximum values absolutely. It is therefore possible that even after thismethodis called the total width of the columns is still not equal to the width of the table. When this happens the JTable does not put itself in AUTO_RESIZE_OFF mode to bring up a scroll bar or break other commitments of its current auto-resize mode --insteadit allows its bounds to be set larger (or smaller) than the total of the column minimum or maximum meaning either that there will not be enough room to display all of the columns or that the columns will not fill the JTable's bounds. These respectively result in the clipping of some columns or an area being painted in the JTable's background color during painting. The mechanism for distributing the delta amongst the available columns is provided in a private method in the JTable class: adjustSizes(long targetSize final Resizable3 r boolean inverse) an explanation of which is provided in the following section. Resizable3 is a private interface that allows any data structure containing a collection of elements with a size preferred size maximum size and minimum size to have its elements manipulated by the algorithm. Distributing the delta Overview Call "DELTA" the difference between the target size and the sum of the preferred sizes of the elements in r. The individual sizes are calculated by taking the original preferred sizes and adding a share of the DELTA - that share being based on how far each preferred size is from its limiting bound (minimum or maximum). Definition Call the individual constraints min[i] max[i] and pref[i]. Call their respective sums: MIN MAX and PREF. Each new size will be calculated using: size[i] = pref[i] + delta[i] where each individual delta[i] is calculated according to: If (DELTA 0) we are in shrink mode where: DELTA delta[i] = ------------ * (pref[i] - min[i]) (PREF - MIN) If (DELTA 0) we are in expand mode where: DELTA delta[i] = ------------ * (max[i] - pref[i]) (MAX - PREF) The overall effect is that the total size moves that same percentage k towards the total minimum or maximum and that percentage guarantees accomodation of the required space DELTA. Details Naive evaluation of the formulae presented here would be subject to the aggregated rounding errors caused by doing this operation in finite precision (using ints). To deal with this the multiplying factor above is constantly recalculated and this takes account of the rounding errors in the previous iterations. The result is an algorithm that produces a set of integers whose values exactly sum to the supplied targetSize and does so by spreading the rounding errors evenly over the given elements. When the MAX and MIN bounds are hit When targetSize is outside the [MIN MAX] range the algorithm sets all sizes to their appropriate limiting value (maximum or minimum). @param resizingColumn the column whose resizing made this adjustment necessary or -1 if there is no such column @seeTableColumn#setWidthdoLayout
Invoked when this table'sTableModelgenerates aTableModelEvent. TheTableModelEventshould be constructed in the coordinate system of the model; the appropriate mapping to the view coordinate system is performed by thisJTablewhen it receives the event.Application code will not use these methods explicitly they are used internally by
JTable.Note that as of 1.3 this method clears the selection if any
.
ATextAreaJTextAreais 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 morecapabilititescapabilities 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 fortherowsorcolumnsis 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 the'JTextComponentbased 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A multi-line area that displays plain text. @author Timothy Prinzing @version 1.69 0483 12/0603/0001 @see JTextPane @see JEditorPane
This class implements accessibility support for theJTextAreaclass. It provides an implementation of the Java Accessibility API appropriate to text area user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Determines the number of lines contained in the area. @return the number of lines >Class JTextArea, boolean getLineWrap()=0
Gets the line-wrapping policy of the text area. If set to true the lines will be wrapped if they are too long to fit within the allocated width. If set to false the lines will always be unwrapped. @Class JTextArea, int getScrollableUnitIncrement(Rectangle, int, int)returnsreturn if lines will be wrapped.
Components that display logical rows or columns should compute the scroll increment that will completely expose one new row or column depending on the value of orientation. This is implemented to use theClass JTextArea, boolean getWrapStyleWord()vaulesvalues returned by thegetRowHeightandgetColumnWidthmethods.Scrolling containers like JScrollPane will use this method each time the user requests a unit scroll. @param visibleRect the view area visible within the viewport @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL. @param direction Less than zero to scroll up/left greater than zero for down/right. @return The "unit" increment for scrolling in the specified direction @exception IllegalArgumentException for an invalid orientation @see JScrollBar#setUnitIncrement @see #getRowHeight @see #getColumnWidth
Class JTextArea, boolean isManagingFocus()GetGets the style of wrapping used if the text area is wrapping lines. If set to true the lines will be wrapped at word boundaries (ie whitespace) if they are too long to fit within the allocated width. If set to false the lines will be wrapped at character boundaries. @returnsreturn if the wrap style should be word boundaries instead of character boundaries.@see #setWrapStyleWord
Class JTextArea, void processKeyEvent(KeyEvent)Turns offChanges thistabJComponent's focus traversaloncekeys to CTRL+TAB and CTRL+SHIFT+TAB. Also preventsSortingFocusTraversalPolicyfrom considering descendants of this JComponent when computing a focusgainedtraversal cycle. @returnsee java.awt.Component#setFocusTraversalKeystrue@seetoSortingFocusTraversalPolicyindicate@deprecatedthat theAs offocus1.4 replacedisbybeingComponent.setFocusTraversalKeys(int Set)andmanagedContainer.setFocusCycleRoot(boolean).
Class JTextArea, void setLineWrap(boolean)MakeOverridessureprocessKeyEventthat TABto processand Shift-TABeventsget consumed so that awt doesn't attempt focus traversal.
Sets the line-wrapping policy of the text area. If set to true the lines will be wrapped if they are too long to fit within the allocated width. If set to false the lines will always be unwrapped. AClass JTextArea, void setWrapStyleWord(boolean)PropertyChangeevent ("lineWrap") is fired when the policy is changed. By default this property is false. @param wrap indicates if lines should be wrapped.@see #getLineWrap @beaninfo preferred: true bound: true description: should lines be wrapped
SetSets the style of wrapping used if the text area is wrapping lines. If set to true the lines will be wrapped at word boundaries (whitespace) if they are too long to fit within the allocated width. If set to false the lines will be wrapped at character boundaries. By default this property is false. @param word indicates if word boundaries should be used for line wrapping.@see #getWrapStyleWord @beaninfo preferred: false bound: true description: should wrapping occur at word boundaries
JTextFieldis a lightweight component that allows the editing of a single line of text. For information on and examples of using text fields see How to Use Text Fields in The Java Tutorial.
JTextFieldis intended to be source-compatible withjava.awt.TextFieldwhere it is reasonable to do so. This component has capabilities not found in thejava.awt.TextFieldclass. The superclass should be consulted for additional capabilities.
JTextFieldhas a method to establish the string used as the command string for the action event that gets fired. Thejava.awt.TextFieldused the text of the field as the command string for theActionEvent.JTextFieldwill use the command string set with thesetActionCommandmethod if notnullotherwise it will use the text of the field as a compatibility withjava.awt.TextField.The method
setEchoCharandgetEchoCharare not provided directly to avoid a new implementation of a pluggable look-and-feel inadvertently exposing password characters. To provide password-like services a separate classJPasswordFieldextendsJTextFieldto provide this service with an independently pluggable look-and-feel.The
java.awt.TextFieldcould be monitored for changes by adding aTextListenerforTextEvent's. 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 = ; JTextField myArea = ; myArea.getDocument().addDocumentListener(myListener);The horizontal alignment of
JTextFieldcan be set to be left justified leading justified centered right justified or trailing justified. Right/trailing justification is useful if the required size of the field text is smaller than the size allocated to it. This is determined by thesetHorizontalAlignmentandgetHorizontalAlignmentmethods. The default is to be leading justified.For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions see the
JTextFieldkey assignments.How the text field consumes VK_ENTER events depends on whether the text field has any action listeners. If so then VK_ENTER results in the listeners getting an ActionEvent and the VK_ENTER event is consumed. This is compatible with how AWT text fields handle VK_ENTER events. If the text field has no action listeners then as of v 1.3 the VK_ENTER event is not consumed. Instead the bindings of ancestor components are processed which enables the default button feature of JFC/Swing to work.
Customized fields can easily be created by extending the model and changing the default model provided. For example the following piece of code will create a field that holds only upper case characters. It will work even if text is pasted into from the clipboard or it is altered via programmatic changes.
public class UpperCaseField extends JTextField { public UpperCaseField(int cols) { super(cols); } protected Document createDefaultModel() { return new UpperCaseDocument(); } static class UpperCaseDocument extends PlainDocument { public void insertString(int offs String str AttributeSet a) throws BadLocationException { if (str == null) { return; } char[] upper = str.toCharArray(); for (int i = 0; iWarning: 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.
A future releaseAs ofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder @beaninfo attribute: isContainer false description: A component which allows for the editing of a single line of text. @author Timothy Prinzing @version 1.72 0485 12/0603/0001 @see #setActionCommand @see JPasswordField @see #addActionListener
This class implements accessibility support for theJTextFieldclass. It provides an implementation of the Java Accessibility API appropriate to text field user-interface elements.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.
AAsfuture releaseofSwing will provide1.4 support for long termpersistencestorage of all JavaBeansTM has been added to thejava.beanspackage. Please see java.beans.XMLEncoder
Constructs a newClass JTextField, constructor JTextField(Document, String, int)TextField. A default model is created the initial string isnulland the number of columns is set to 0.
Constructs a newClass JTextField, constructor JTextField(String)JTextFieldthat uses the given text storage model and the given number of columns. This is the constructor through which the other constructors feed. If the document isnulla default model is created. @param doc the text storage to use. If; if this isnulla default will be provided by calling thecreateDefaultModelmethod.@param text the initial string to display ornull@param columns the number of columns to use to calculate the preferred width >= 0. If; ifcolumnsis set to zero the preferred width will be whatever naturally results from the component implementation.@exception IllegalArgumentException ifcolumns<0
Constructs a newClass JTextField, constructor JTextField(String, int)TextFieldinitialized with the specified text. A default model is created and the number of columns is 0. @param text the text to be displayed ornull
Constructs a newClass JTextField, constructor JTextField(int)TextFieldinitialized with the specified text and columns. A default model is created. @param text the text to be displayed ornull@param columns the number of columns to use to calculate the preferred width. If; if columns is set to zero the preferred width will be whatever naturally results from the component implementation.
Constructs a new emptyClass JTextField, void addActionListener(ActionListener)TextFieldwith the specified number of columns. A default model is created and the initial string is set tonull. @param columns the number of columns to use to calculate the preferred width. If; if columns is set to zero the preferred width will be whatever naturally results from the component implementation.
Adds the specified action listener to receive action events from this textfield. @param l the action listener to be addedClass JTextField, void configurePropertiesFromAction(Action)
Factory method which sets theClass JTextField, PropertyChangeListener createActionPropertyChangeListener(Action)ActionEventsource's properties according to values from theActioninstance. The properties which are set may differ for subclasses. By default the properties which get set areEnabledandToolTipText. @param a theActionfrom which to get the properties ornull@since 1.3 @see Action @see #setAction
Factory method which creates theClass JTextField, Document createDefaultModel()PropertyChangeListenerused to update theActionEventsource as properties change on itsActioninstance. Subclasses may override this in order to provide their ownPropertyChangeListenerif the set of properties which should be kept up to date differs from the default properties (Text Enabled ToolTipText).Note that
PropertyChangeListenersshould avoid holding strong references to theActionEventsource as this may hinder garbage collection of theActionEventsource and all components in its containment hierarchy. @param a theActionfrom which to get the properties ornull@since 1.3 @see Action @see #setAction
Creates the default implementation of the model to be used at construction if one isn't explicitly given. An instance of PlainDocument is returned. @return the default model implementation
Class JTextField, void fireActionPerformed()Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily createdusing the parameters passed into the fire method. The listener list is processed in last to first order. @see EventListenerList