- All Implemented Interfaces:
- ImageObserver,- MenuContainer,- Serializable
- Direct Known Subclasses:
- AbstractButton,- BasicInternalFrameTitlePane,- Box,- Box.Filler,- JColorChooser,- JComboBox,- JFileChooser,- JInternalFrame,- JInternalFrame.JDesktopIcon,- JLabel,- JLayer,- JLayeredPane,- JList,- JMenuBar,- JOptionPane,- JPanel,- JPopupMenu,- JProgressBar,- JRootPane,- JScrollBar,- JScrollPane,- JSeparator,- JSlider,- JSpinner,- JSplitPane,- JTabbedPane,- JTable,- JTableHeader,- JTextComponent,- JToolBar,- JToolTip,- JTree,- JViewport
JComponent,
 you must place the component in a containment hierarchy
 whose root is a top-level Swing container.
 Top-level Swing containers --
 such as JFrame, JDialog,
 and JApplet --
 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 JComponent class provides:
 
- 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
     ComponentUI. See How to Set the Look and Feel in The Java Tutorial for more information.
- Comprehensive keystroke handling. See the document How to Use Key Bindings, an article in The Java Tutorial, 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(java.lang.Object, java.lang.Object)andgetClientProperty(java.lang.Object)methods, you can associate name-object pairs with any object that descends fromJComponent.
- 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.
Swing package description
 and The Java Tutorial section
 The JComponent Class.
 
 JComponent and its subclasses document default values
 for certain properties.  For example, JTable documents the
 default row height as 16.  Each JComponent subclass
 that has a ComponentUI will create the
 ComponentUI as part of its constructor.  In order
 to provide a particular look and feel each
 ComponentUI may set properties back on the
 JComponent that created it.  For example, a custom
 look and feel may require JTables to have a row
 height of 24. The documented defaults are the value of a property
 BEFORE the ComponentUI has been installed.  If you
 need a specific value for a particular property you should
 explicitly set it.
 
In release 1.4, the focus subsystem was rearchitected. For more information, see How to Use the Focus Subsystem, a section in The Java Tutorial.
Warning: Swing is not thread safe. For more information see Swing's Threading Policy.
 Warning:
 Serialized objects of this class will not be compatible with
 future Swing releases. The current serialization support is
 appropriate for short term storage or RMI between applications running
 the same version of Swing.  As of 1.4, support for long term storage
 of all JavaBeans
 has been added to the java.beans package.
 Please see XMLEncoder.
- 
Nested Class SummaryNested ClassesModifier and TypeClassDescriptionclassInner class of JComponent used to provide default support for accessibility.Nested classes/interfaces declared in class java.awt.ContainerContainer.AccessibleAWTContainerNested classes/interfaces declared in class java.awt.ComponentComponent.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
- 
Field SummaryFieldsModifier and TypeFieldDescriptionprotected EventListenerListA list of event listeners for this component.static final StringThe comment to display when the cursor is over the component, also known as a "value tip", "flyover help", or "flyover label".protected ComponentUIThe look and feel delegate for this component.static final intConstant used by some of the APIs to mean that no condition is defined.static final intConstant used forregisterKeyboardActionthat means that the command should be invoked when the receiving component is an ancestor of the focused component or is itself the focused component.static final intConstant used forregisterKeyboardActionthat means that the command should be invoked when the component has the focus.static final intConstant used forregisterKeyboardActionthat 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.Fields declared in class java.awt.ComponentaccessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields declared in interface java.awt.image.ImageObserverABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
- 
Constructor SummaryConstructors
- 
Method SummaryModifier and TypeMethodDescriptionvoidaddAncestorListener(AncestorListener listener) Registerslistenerso that it will receiveAncestorEventswhen it or any of its ancestors move or are made visible or invisible.voidNotifies this component that it now has a parent component.voidAdds aVetoableChangeListenerto the listener list.voidcomputeVisibleRect(Rectangle visibleRect) Returns theComponent's "visible rect rectangle" - the intersection of the visible rectangles for this component and all of its ancestors.booleancontains(int x, int y) Gives the UI delegate an opportunity to define the precise shape of this component for the sake of mouse processing.Returns the instance ofJToolTipthat should be used to display the tooltip.voiddisable()Deprecated.voidenable()Deprecated.As of JDK version 1.1, replaced byjava.awt.Component.setEnabled(boolean).voidfirePropertyChange(String propertyName, boolean oldValue, boolean newValue) Support for reporting bound property changes for boolean properties.voidfirePropertyChange(String propertyName, int oldValue, int newValue) Support for reporting bound property changes for integer properties.protected voidfireVetoableChange(String propertyName, Object oldValue, Object newValue) Supports reporting constrained property changes.getActionForKeyStroke(KeyStroke aKeyStroke) Returns the object that will perform the action registered for a given keystroke.final ActionMapReturns theActionMapused to determine whatActionto fire for particularKeyStrokebinding.floatOverridesContainer.getAlignmentXto return the horizontal alignment.floatOverridesContainer.getAlignmentYto return the vertical alignment.Returns an array of all the ancestor listeners registered on this component.booleanGets theautoscrollsproperty.intgetBaseline(int width, int height) Returns the baseline.Returns an enum indicating how the baseline of the component changes as the size changes.Returns the border of this component ornullif no border is currently set.Stores the bounds of this component into "return value"rvand returnsrv.final ObjectgetClientProperty(Object key) Returns the value of the property with the specified key.protected GraphicsReturns the graphics object used to paint this component.ReturnsJPopupMenuthat assigned for this component.intgetConditionForKeyStroke(KeyStroke aKeyStroke) Returns the condition that determines whether a registered action occurs in response to the specified keystroke.intReturns the state of graphics debugging.static LocaleReturns the default locale used to initialize each JComponent's locale property upon creation.getFontMetrics(Font font) Gets theFontMetricsfor the specifiedFont.Returns this component's graphics context, which lets you draw on a component.intReturns the current height of this component.booleanReturns true if the JPopupMenu should be inherited from the parent.final InputMapReturns theInputMapthat is used when the component has focus.final InputMapgetInputMap(int condition) Returns theInputMapthat is used duringcondition.Returns the input verifier for this component.If a border has been set on this component, returns the border's insets; otherwise callssuper.getInsets.Returns anInsetsobject containing this component's inset values.<T extends EventListener>
 T[]getListeners(Class<T> listenerType) Returns an array of all the objects currently registered asFooListeners upon thisJComponent.getLocation(Point rv) Stores the x,y origin of this component into "return value"rvand returnsrv.If the maximum size has been set to a non-nullvalue just returns it.If the minimum size has been set to a non-nullvalue just returns it.Deprecated.As of 1.4, replaced byFocusTraversalPolicy.getPopupLocation(MouseEvent event) Returns the preferred location to display the popup menu in this component's coordinate system.If thepreferredSizehas been set to a non-nullvalue just returns it.Returns theKeyStrokesthat will initiate registered actions.Returns theJRootPaneancestor for this component.Stores the width/height of this component into "return value"rvand returnsrv.getToolTipLocation(MouseEvent event) Returns the tooltip location in this component's coordinate system.Returns the tooltip string that has been set withsetToolTipText.getToolTipText(MouseEvent event) Returns the string to be used as the tooltip for event.Returns the top-level ancestor of this component (either the containingWindoworApplet), ornullif this component has not been added to any container.Gets thetransferHandlerproperty.getUI()Returns the look and feel delegate that renders this component.Returns theUIDefaultskey used to look up the name of theswing.plaf.ComponentUIclass that defines the look and feel for this component.booleanReturns the value that indicates whether the input verifier for the current focus owner will be called before this component requests focus.Returns an array of all the vetoable change listeners registered on this component.Returns theComponent's "visible rectangle" - the intersection of this component's visible rectangle,new Rectangle(0, 0, getWidth(), getHeight()), and all of its ancestors' visible rectangles.intgetWidth()Returns the current width of this component.intgetX()Returns the current x coordinate of the component's origin.intgetY()Returns the current y coordinate of the component's origin.voidRequests that this Component get the input focus, and that this Component's top-level ancestor become the focused Window.voidhide()Deprecated.booleanReturns whether this component should use a buffer to paint.static booleanReturns true if this component is lightweight, that is, if it doesn't have a native window system peer.booleanDeprecated.As of 1.4, replaced byComponent.setFocusTraversalKeys(int, Set)andContainer.setFocusCycleRoot(boolean).booleanisOpaque()Returns true if this component is completely opaque.booleanReturns true if this component tiles its children -- that is, if it can guarantee that the children will not overlap.final booleanReturnstrueif the current painting operation on this component is part of aprintoperation.protected booleanReturnstrueif a paint triggered on a child component should cause painting to originate from this Component, or one of its ancestors.booleanReturns true if the component is currently painting a tile.booleanReturnstrueif thisJComponentshould get focus; otherwise returnsfalse.booleanIf this method returns true,revalidatecalls by descendants of this component will cause the entire tree beginning with this root to be validated.voidInvoked by Swing to draw components.protected voidPaints the component's border.protected voidPaints this component's children.protected voidCalls the UI delegate's paint method, if the UI delegate is non-null.voidpaintImmediately(int x, int y, int w, int h) Paints the specified region in this component and all of its descendants that overlap the region, immediately.voidPaints the specified region now.protected StringReturns a string representation of thisJComponent.voidInvoke this method to print the component to the specifiedGraphics.voidInvoke this method to print the component.protected voidPrints the component's border.protected voidPrints this component's children.protected voidThis is invoked during a printing operation.protected voidProcesses any key events that the component itself recognizes.protected booleanprocessKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) Invoked to process the key bindings forksas the result of theKeyEvente.protected voidOverridesprocessKeyEventto process events.protected voidProcesses mouse events occurring on this component by dispatching them to any registeredMouseListenerobjects, refer toComponent.processMouseEvent(MouseEvent)for a complete description of this method.protected voidProcesses mouse motion events, such as MouseEvent.MOUSE_DRAGGED.final voidputClientProperty(Object key, Object value) Adds an arbitrary key/value "client property" to this component.voidregisterKeyboardAction(ActionListener anAction, String aCommand, KeyStroke aKeyStroke, int aCondition) This method is now obsolete, please use a combination ofgetActionMap()andgetInputMap()for similar behavior.voidregisterKeyboardAction(ActionListener anAction, KeyStroke aKeyStroke, int aCondition) This method is now obsolete, please use a combination ofgetActionMap()andgetInputMap()for similar behavior.voidremoveAncestorListener(AncestorListener listener) Unregisterslistenerso that it will no longer receiveAncestorEvents.voidNotifies this component that it no longer has a parent component.voidRemoves aVetoableChangeListenerfrom the listener list.voidrepaint(long tm, int x, int y, int width, int height) Adds the specified region to the dirty region list if the component is showing.voidAdds the specified region to the dirty region list if the component is showing.booleanDeprecated.As of 1.4, replaced byFocusTraversalPolicy.getDefaultComponent(Container).requestFocus()voidRequests that thisComponentgets the input focus.booleanrequestFocus(boolean temporary) Requests that thisComponentgets the input focus.booleanRequests that thisComponentgets the input focus.protected booleanrequestFocusInWindow(boolean temporary) Requests that thisComponentgets the input focus.voidUnregisters all the bindings in the first tierInputMapsandActionMap.voidreshape(int x, int y, int w, int h) Deprecated.As of JDK 5, replaced byComponent.setBounds(int, int, int, int).voidSupports deferred automatic layout.voidscrollRectToVisible(Rectangle aRect) Forwards thescrollRectToVisible()message to theJComponent's parent.final voidSets theActionMaptoam.voidsetAlignmentX(float alignmentX) Sets the horizontal alignment.voidsetAlignmentY(float alignmentY) Sets the vertical alignment.voidsetAutoscrolls(boolean autoscrolls) Sets theautoscrollsproperty.voidsetBackground(Color bg) Sets the background color of this component.voidSets the border of this component.voidsetComponentPopupMenu(JPopupMenu popup) Sets theJPopupMenufor thisJComponent.voidsetDebugGraphicsOptions(int debugOptions) Enables or disables diagnostic information about every graphics operation performed within the component or one of its children.static voidSets the default locale used to initialize each JComponent's locale property upon creation.voidsetDoubleBuffered(boolean aFlag) Sets whether this component should use a buffer to paint.voidsetEnabled(boolean enabled) Sets whether or not this component is enabled.voidsetFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes) Sets the focus traversal keys for a given traversal operation for this Component.voidSets the font for this component.voidsetForeground(Color fg) Sets the foreground color of this component.voidsetInheritsPopupMenu(boolean value) Sets whether or notgetComponentPopupMenushould delegate to the parent if this component does not have aJPopupMenuassigned to it.final voidsetInputMap(int condition, InputMap map) Sets theInputMapto use under the conditionconditiontomap.voidsetInputVerifier(InputVerifier inputVerifier) Sets the input verifier for this component.voidsetMaximumSize(Dimension maximumSize) Sets the maximum size of this component to a constant value.voidsetMinimumSize(Dimension minimumSize) Sets the minimum size of this component to a constant value.voidsetNextFocusableComponent(Component aComponent) Deprecated.As of 1.4, replaced byFocusTraversalPolicyvoidsetOpaque(boolean isOpaque) If true the component paints every pixel within its bounds.voidsetPreferredSize(Dimension preferredSize) Sets the preferred size of this component.voidsetRequestFocusEnabled(boolean requestFocusEnabled) Provides a hint as to whether or not thisJComponentshould get focus.voidsetToolTipText(String text) Registers the text to display in a tool tip.voidsetTransferHandler(TransferHandler newHandler) Sets theTransferHandler, which provides support for transfer of data into and out of this component via cut/copy/paste and drag and drop.protected voidsetUI(ComponentUI newUI) Sets the look and feel delegate for this component.voidsetVerifyInputWhenFocusTarget(boolean verifyInputWhenFocusTarget) Sets the value to indicate whether input verifier for the current focus owner will be called before this component requests focus.voidsetVisible(boolean aFlag) Makes the component visible or invisible.voidunregisterKeyboardAction(KeyStroke aKeyStroke) This method is now obsolete.voidCallspaint.voidupdateUI()This method is called to update the UI property to a value from the current look and feel.Methods declared in class java.awt.Containeradd, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTreeMethods declared in class java.awt.Componentaction, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAccessibleContext, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
- 
Field Details- 
uiThe look and feel delegate for this component.
- 
listenerListA list of event listeners for this component.
- 
WHEN_FOCUSEDpublic static final int WHEN_FOCUSEDConstant used forregisterKeyboardActionthat means that the command should be invoked when the component has the focus.- See Also:
 
- 
WHEN_ANCESTOR_OF_FOCUSED_COMPONENTpublic static final int WHEN_ANCESTOR_OF_FOCUSED_COMPONENTConstant used forregisterKeyboardActionthat means that the command should be invoked when the receiving component is an ancestor of the focused component or is itself the focused component.- See Also:
 
- 
WHEN_IN_FOCUSED_WINDOWpublic static final int WHEN_IN_FOCUSED_WINDOWConstant used forregisterKeyboardActionthat 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.- See Also:
 
- 
UNDEFINED_CONDITIONpublic static final int UNDEFINED_CONDITIONConstant used by some of the APIs to mean that no condition is defined.- See Also:
 
- 
TOOL_TIP_TEXT_KEYThe comment to display when the cursor is over the component, also known as a "value tip", "flyover help", or "flyover label".- See Also:
 
 
- 
- 
Constructor Details- 
JComponentpublic JComponent()DefaultJComponentconstructor. This constructor does very 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 Also:
 
 
- 
- 
Method Details- 
setInheritsPopupMenu@BeanProperty(description="Whether or not the JPopupMenu is inherited") public void setInheritsPopupMenu(boolean value) Sets whether or notgetComponentPopupMenushould delegate to the parent if this component does not have aJPopupMenuassigned to it.The default value for this is false, but some JComponentsubclasses that are implemented as a number ofJComponents may set this to true.This is a bound property. - Parameters:
- value- whether or not the JPopupMenu is inherited
- Since:
- 1.5
- See Also:
 
- 
getInheritsPopupMenupublic boolean getInheritsPopupMenu()Returns true if the JPopupMenu should be inherited from the parent.- Returns:
- true if the JPopupMenu should be inherited from the parent
- Since:
- 1.5
- See Also:
 
- 
setComponentPopupMenu@BeanProperty(preferred=true, description="Popup to show") public void setComponentPopupMenu(JPopupMenu popup) Sets theJPopupMenufor thisJComponent. The UI is responsible for registering bindings and adding the necessary listeners such that theJPopupMenuwill be shown at the appropriate time. When theJPopupMenuis shown depends upon the look and feel: some may show it on a mouse event, some may enable a key binding.If popupis null, andgetInheritsPopupMenureturns true, thengetComponentPopupMenuwill be delegated to the parent. This provides for a way to make all child components inherit the popupmenu of the parent.This is a bound property. - Parameters:
- popup- - the popup that will be assigned to this component may be null
- Since:
- 1.5
- See Also:
 
- 
getComponentPopupMenuReturnsJPopupMenuthat assigned for this component. If this component does not have aJPopupMenuassigned to it andgetInheritsPopupMenuis true, this will returngetParent().getComponentPopupMenu()(assuming the parent is valid.)- Returns:
- JPopupMenuassigned for this component or- nullif no popup assigned
- Since:
- 1.5
- See Also:
 
- 
updateUIpublic void updateUI()This method is called to update the UI property to a value from the current look and feel.JComponentsubclasses must override this method like this:public void updateUI() { setUI((SliderUI)UIManager.getUI(this); }- Implementation Requirements:
- The default implementation of this method does nothing.
- See Also:
 
- 
getUIReturns the look and feel delegate that renders this component.- Returns:
- the ComponentUIobject that renders this component
- Since:
- 9
 
- 
setUI@BeanProperty(hidden=true, visualUpdate=true, description="The component\'s look and feel delegate.") protected void setUI(ComponentUI newUI) Sets the look and feel delegate for this component.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; }- Parameters:
- newUI- the new UI delegate
- See Also:
 
- 
getUIClassIDReturns theUIDefaultskey 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.- Returns:
- the UIDefaultskey for aComponentUIsubclass
- See Also:
 
- 
getComponentGraphicsReturns the graphics object used to paint this component. IfDebugGraphicsis turned on we create a newDebugGraphicsobject if necessary. Otherwise we just configure the specified graphics object's foreground and font.- Parameters:
- g- the original- Graphicsobject
- Returns:
- a Graphicsobject configured for this component
 
- 
paintComponentCalls the UI delegate's paint method, if the UI delegate is non-null. We pass the delegate a copy of theGraphicsobject to protect the rest of the paint code from irrevocable changes (for example,Graphics.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 invoke super's implementation you must honor the opaque property, that is if this component is opaque, you must completely fill in the background in an opaque color. If you do not honor the opaque property you will likely see visual artifacts.The passed in Graphicsobject might have a transform other than the identify transform installed on it. In this case, you might get unexpected results if you cumulatively apply another transform.- Parameters:
- g- the- Graphicsobject to protect
- See Also:
 
- 
paintChildrenPaints this component's children. IfshouldUseBufferis 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.- Parameters:
- g- the- Graphicscontext in which to paint
- See Also:
 
- 
paintBorderPaints the component's border.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.- Parameters:
- g- the- Graphicscontext in which to paint
- See Also:
 
- 
updateCallspaint. Doesn't clear the background but seeComponentUI.update, which is called bypaintComponent.
- 
paintInvoked by 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: paintComponent,paintBorder, andpaintChildren. 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.
- 
printAllInvoke this method to print the component. This method invokesprinton the component.
- 
printInvoke this method to print the component to the specifiedGraphics. This method will result in invocations ofprintComponent,printBorderandprintChildren. It is recommended that you override one of the previously mentioned methods rather than this one if your intention is to customize the way printing looks. However, it can be useful to override this method should you want to prepare state before invoking the superclass behavior. As an example, if you wanted to change the component's background color before printing, you could do the following:public void print(Graphics g) { Color orig = getBackground(); setBackground(Color.WHITE); // wrap in try/finally so that we always restore the state try { super.print(g); } finally { setBackground(orig); } }Alternatively, or for components that delegate painting to other objects, you can query during painting whether or not the component is in the midst of a print operation. The isPaintingForPrintmethod provides this ability and its return value will be changed by this method: totrueimmediately before rendering and tofalseimmediately after. With each change a property change event is fired on this component with the name"paintingForPrint".This method sets the component's state such that the double buffer will not be used: painting will be done directly on the passed in Graphics.
- 
printComponentThis is invoked during a printing operation. This is implemented to invokepaintComponenton the component. Override this if you wish to add special painting behavior when printing.- Parameters:
- g- the- Graphicscontext in which to paint
- Since:
- 1.3
- See Also:
 
- 
printChildrenPrints this component's children. This is implemented to invokepaintChildrenon the component. Override this if you wish to print the children differently than painting.- Parameters:
- g- the- Graphicscontext in which to paint
- Since:
- 1.3
- See Also:
 
- 
printBorderPrints the component's border. This is implemented to invokepaintBorderon the component. Override this if you wish to print the border differently that it is painted.- Parameters:
- g- the- Graphicscontext in which to paint
- Since:
- 1.3
- See Also:
 
- 
isPaintingTileReturns true if the component 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.- Returns:
- true if the component is currently painting a tile, false otherwise
 
- 
isPaintingForPrintReturnstrueif the current painting operation on this component is part of aprintoperation. This method is useful when you want to customize what you print versus what you show on the screen.You can detect changes in the value of this property by listening for property change events on this component with name "paintingForPrint".Note: This method provides complimentary functionality to that provided by other high level Swing printing APIs. However, it deals strictly with painting and should not be confused as providing information on higher level print processes. For example, a JTable.print()operation doesn't necessarily result in a continuous rendering of the full component, and the return value of this method can change multiple times during that operation. It is even possible for the component to be painted to the screen while the printing process is ongoing. In such a case, the return value of this method istruewhen, and only when, the table is being painted as part of the printing process.- Returns:
- true if the current painting operation on this component is part of a print operation
- Since:
- 1.6
- See Also:
 
- 
isManagingFocusDeprecated.As of 1.4, replaced byComponent.setFocusTraversalKeys(int, Set)andContainer.setFocusCycleRoot(boolean).In release 1.4, the focus subsystem was rearchitected. For more information, see How to Use the Focus Subsystem, a section in The Java Tutorial.Changes this JComponent's focus traversal keys to CTRL+TAB and CTRL+SHIFT+TAB. Also preventsSortingFocusTraversalPolicyfrom considering descendants of this JComponent when computing a focus traversal cycle.
- 
setNextFocusableComponentDeprecated.As of 1.4, replaced byFocusTraversalPolicyIn release 1.4, the focus subsystem was rearchitected. For more information, see How to Use the Focus Subsystem, a section in The Java Tutorial.Overrides the default FocusTraversalPolicyfor thisJComponent's focus traversal cycle by unconditionally setting the specifiedComponentas the nextComponentin the cycle, and thisJComponentas the specifiedComponent's previousComponentin the cycle.- Parameters:
- aComponent- the- Componentthat should follow this- JComponentin the focus traversal cycle
- See Also:
 
- 
getNextFocusableComponentDeprecated.As of 1.4, replaced byFocusTraversalPolicy.In release 1.4, the focus subsystem was rearchitected. For more information, see How to Use the Focus Subsystem, a section in The Java Tutorial.Returns the Componentset by a prior call tosetNextFocusableComponent(Component)on thisJComponent.- Returns:
- the Componentthat will follow thisJComponentin the focus traversal cycle, ornullif none has been explicitly specified
- See Also:
 
- 
setRequestFocusEnabledpublic void setRequestFocusEnabled(boolean requestFocusEnabled) Provides a hint as to whether or not thisJComponentshould get focus. This is only a hint, and it is up to consumers that are requesting focus to honor this property. This is typically honored for mouse operations, but not keyboard operations. For example, look and feels could verify this property is true before requesting focus during a mouse operation. This would often times be used if you did not want a mouse press on aJComponentto steal focus, but did want theJComponentto be traversable via the keyboard. If you do not want thisJComponentfocusable at all, use thesetFocusablemethod instead.Please see How to Use the Focus Subsystem, a section in The Java Tutorial, for more information. - Parameters:
- requestFocusEnabled- indicates whether you want this- JComponentto be focusable or not
- See Also:
 
- 
isRequestFocusEnabledpublic boolean isRequestFocusEnabled()Returnstrueif thisJComponentshould get focus; otherwise returnsfalse.Please see How to Use the Focus Subsystem, a section in The Java Tutorial, for more information. - Returns:
- trueif this component should get focus, otherwise returns- false
- See Also:
 
- 
requestFocuspublic void requestFocus()Requests that thisComponentgets the input focus. Refer toComponent.requestFocus()for a complete description of this method.Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of requestFocusInWindow(). If you would like more information on focus, see How to Use the Focus Subsystem, a section in The Java Tutorial.- Overrides:
- requestFocusin class- Component
- Since:
- 1.4
- See Also:
 
- 
requestFocuspublic boolean requestFocus(boolean temporary) Requests that thisComponentgets the input focus. Refer toComponent.requestFocus(boolean)for a complete description of this method.Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of requestFocusInWindow(boolean). If you would like more information on focus, see How to Use the Focus Subsystem, a section in The Java Tutorial.- Overrides:
- requestFocusin class- Component
- Parameters:
- temporary- boolean indicating if the focus change is temporary
- Returns:
- falseif the focus change request is guaranteed to fail;- trueif it is likely to succeed
- Since:
- 1.4
- See Also:
 
- 
requestFocusInWindowpublic boolean requestFocusInWindow()Requests that thisComponentgets the input focus. Refer toComponent.requestFocusInWindow()for a complete description of this method.If you would like more information on focus, see How to Use the Focus Subsystem, a section in The Java Tutorial. - Overrides:
- requestFocusInWindowin class- Component
- Returns:
- falseif the focus change request is guaranteed to fail;- trueif it is likely to succeed
- Since:
- 1.4
- See Also:
 
- 
requestFocusInWindowprotected boolean requestFocusInWindow(boolean temporary) Requests that thisComponentgets the input focus. Refer toComponent.requestFocusInWindow(boolean)for a complete description of this method.If you would like more information on focus, see How to Use the Focus Subsystem, a section in The Java Tutorial. - Overrides:
- requestFocusInWindowin class- Component
- Parameters:
- temporary- boolean indicating if the focus change is temporary
- Returns:
- falseif the focus change request is guaranteed to fail;- trueif it is likely to succeed
- Since:
- 1.4
- See Also:
 
- 
grabFocuspublic void grabFocus()Requests that this Component get the input focus, and that this Component's top-level ancestor become the focused Window. This component must be displayable, visible, and focusable for the request to be granted.This method is intended for use by focus implementations. Client code should not use this method; instead, it should use requestFocusInWindow().- See Also:
 
- 
setVerifyInputWhenFocusTarget@BeanProperty(description="Whether the Component verifies input before accepting focus.") public void setVerifyInputWhenFocusTarget(boolean verifyInputWhenFocusTarget) Sets 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.- Parameters:
- verifyInputWhenFocusTarget- value for the- verifyInputWhenFocusTargetproperty
- Since:
- 1.3
- See Also:
 
- 
getVerifyInputWhenFocusTargetpublic boolean getVerifyInputWhenFocusTarget()Returns the value that indicates whether the input verifier for the current focus owner will be called before this component requests focus.- Returns:
- value of the verifyInputWhenFocusTargetproperty
- Since:
- 1.3
- See Also:
 
- 
getFontMetricsGets theFontMetricsfor the specifiedFont.- Overrides:
- getFontMetricsin class- Component
- Parameters:
- font- the font for which font metrics is to be obtained
- Returns:
- the font metrics for font
- Throws:
- NullPointerException- if- fontis null
- Since:
- 1.5
- See Also:
- 
- Component.getFont()
- ComponentPeer.getFontMetrics(Font)
- Toolkit.getFontMetrics(Font)
 
 
- 
setPreferredSize@BeanProperty(preferred=true, description="The preferred size of the component.") public void setPreferredSize(Dimension preferredSize) Sets the preferred size of this component. IfpreferredSizeisnull, the UI will be asked for the preferred size.- Overrides:
- setPreferredSizein class- Component
- Parameters:
- preferredSize- The new preferred size, or null
- See Also:
 
- 
getPreferredSizeIf thepreferredSizehas been set to a non-nullvalue just returns it. If the UI delegate'sgetPreferredSizemethod returns a nonnullvalue then return that; otherwise defer to the component's layout manager.- Overrides:
- getPreferredSizein class- Container
- Returns:
- the value of the preferredSizeproperty
- See Also:
 
- 
setMaximumSize@BeanProperty(description="The maximum size of the component.") public void setMaximumSize(Dimension maximumSize) Sets the maximum size of this component to a constant value. Subsequent calls togetMaximumSizewill always return this value; the component's UI will not be asked to compute it. Setting the maximum size tonullrestores the default behavior.- Overrides:
- setMaximumSizein class- Component
- Parameters:
- maximumSize- a- Dimensioncontaining the desired maximum allowable size
- See Also:
 
- 
getMaximumSizeIf the maximum size has been set to a non-nullvalue just returns it. If the UI delegate'sgetMaximumSizemethod returns a non-nullvalue then return that; otherwise defer to the component's layout manager.- Overrides:
- getMaximumSizein class- Container
- Returns:
- the value of the maximumSizeproperty
- See Also:
 
- 
setMinimumSize@BeanProperty(description="The minimum size of the component.") public void setMinimumSize(Dimension minimumSize) Sets the minimum size of this component to a constant value. Subsequent calls togetMinimumSizewill always return this value; the component's UI will not be asked to compute it. Setting the minimum size tonullrestores the default behavior.- Overrides:
- setMinimumSizein class- Component
- Parameters:
- minimumSize- the new minimum size of this component
- See Also:
 
- 
getMinimumSizeIf the minimum size has been set to a non-nullvalue just returns it. If the UI delegate'sgetMinimumSizemethod returns a non-nullvalue then return that; otherwise defer to the component's layout manager.- Overrides:
- getMinimumSizein class- Container
- Returns:
- the value of the minimumSizeproperty
- See Also:
 
- 
containspublic boolean contains(int x, int y) Gives the UI delegate an opportunity to define the precise shape of this component for the sake of mouse processing.
- 
setBorder@BeanProperty(preferred=true, visualUpdate=true, description="The component\'s border.") public void setBorder(Border border) Sets the border of this component. TheBorderobject 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.Although technically you can set the border on any object that inherits from JComponent, the look and feel implementation of many standard Swing components doesn't work well with user-set borders. In general, when you want to set a border on a standard Swing component other thanJPanelorJLabel, we recommend that you put the component in aJPaneland set the border on theJPanel.This is a bound property. - Parameters:
- border- the border to be rendered for this component
- See Also:
 
- 
getBorderReturns the border of this component ornullif no border is currently set.- Returns:
- the border object for this component
- See Also:
 
- 
getInsetsIf a border has been set on this component, returns the border's insets; otherwise callssuper.getInsets.
- 
getInsetsReturns anInsetsobject 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.- Parameters:
- insets- the- Insetsobject, which can be reused
- Returns:
- the Insetsobject
- See Also:
 
- 
getAlignmentYpublic float getAlignmentY()OverridesContainer.getAlignmentYto return the vertical alignment.- Overrides:
- getAlignmentYin class- Container
- Returns:
- the value of the alignmentYproperty
- See Also:
 
- 
setAlignmentY@BeanProperty(description="The preferred vertical alignment of the component.") public void setAlignmentY(float alignmentY) Sets the vertical alignment.- Parameters:
- alignmentY- the new vertical alignment
- See Also:
 
- 
getAlignmentXpublic float getAlignmentX()OverridesContainer.getAlignmentXto return the horizontal alignment.- Overrides:
- getAlignmentXin class- Container
- Returns:
- the value of the alignmentXproperty
- See Also:
 
- 
setAlignmentX@BeanProperty(description="The preferred horizontal alignment of the component.") public void setAlignmentX(float alignmentX) Sets the horizontal alignment.- Parameters:
- alignmentX- the new horizontal alignment
- See Also:
 
- 
setInputVerifier@BeanProperty(description="The component\'s input verifier.") public void setInputVerifier(InputVerifier inputVerifier) Sets the input verifier for this component.- Parameters:
- inputVerifier- the new input verifier
- Since:
- 1.3
- See Also:
 
- 
getInputVerifierReturns the input verifier for this component.- Returns:
- the inputVerifierproperty
- Since:
- 1.3
- See Also:
 
- 
getGraphicsReturns this component's graphics context, which lets you draw on a component. Use this method to get aGraphicsobject and then invoke operations on that object to draw on the component.- Overrides:
- getGraphicsin class- Component
- Returns:
- this components graphics context
- See Also:
 
- 
setDebugGraphicsOptions@BeanProperty(bound=false, preferred=true, enumerationValues={"DebugGraphics.NONE_OPTION","DebugGraphics.LOG_OPTION","DebugGraphics.FLASH_OPTION","DebugGraphics.BUFFERED_OPTION"}, description="Diagnostic options for graphics operations.") public void setDebugGraphicsOptions(int debugOptions) Enables or disables diagnostic information about every graphics operation performed within the component or one of its children.- Parameters:
- debugOptions- determines how the component should display the 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.
- DebugGraphics.NONE_OPTION disables debugging.
- A value of 0 causes no changes to the debugging options.
 - debugOptionsis bitwise OR'd into the current value
 
- 
getDebugGraphicsOptionspublic int getDebugGraphicsOptions()Returns the state of graphics debugging.- Returns:
- a bitwise OR'd flag of zero or more 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.
- DebugGraphics.NONE_OPTION disables debugging.
- A value of 0 causes no changes to the debugging options.
 
- See Also:
 
- 
registerKeyboardActionpublic void registerKeyboardAction(ActionListener anAction, String aCommand, KeyStroke aKeyStroke, int aCondition) This method is now obsolete, please use a combination ofgetActionMap()andgetInputMap()for similar 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 aConditioncan 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.- Parameters:
- anAction- the- Actionto be registered
- aCommand- the command to be set in the delivered event
- aKeyStroke- the- KeyStroketo bind to the action
- aCondition- the condition that needs to be met, see above
- See Also:
 
- 
registerKeyboardActionThis method is now obsolete, please use a combination ofgetActionMap()andgetInputMap()for similar behavior.- Parameters:
- anAction- action to be registered to given keystroke and condition
- aKeyStroke- a- KeyStroke
- aCondition- the condition to be associated with given keystroke and action
- See Also:
 
- 
unregisterKeyboardActionThis method is now obsolete. To unregister an existing binding you can either remove the binding from theActionMap/InputMap, or place a dummy binding theInputMap. Removing the binding from theInputMapallows bindings in parentInputMaps 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 theInputMaps.- Parameters:
- aKeyStroke- the keystroke for which to unregister its keyboard action
 
- 
getRegisteredKeyStrokesReturns theKeyStrokesthat will initiate registered actions.- Returns:
- an array of KeyStrokeobjects
- See Also:
 
- 
getConditionForKeyStrokeReturns the condition that determines whether a registered action occurs in response to the specified keystroke.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.- Parameters:
- aKeyStroke- the keystroke for which to request an action-keystroke condition
- Returns:
- the action-keystroke condition
 
- 
getActionForKeyStrokeReturns the object that will perform the action registered for a given keystroke.- Parameters:
- aKeyStroke- the keystroke for which to return a listener
- Returns:
- the ActionListenerobject invoked when the keystroke occurs
 
- 
resetKeyboardActionspublic void resetKeyboardActions()Unregisters all the bindings in the first tierInputMapsandActionMap. 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.
- 
setInputMapSets theInputMapto 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).conditionhas one of the following values:- WHEN_IN_FOCUSED_WINDOW
- WHEN_FOCUSED
- WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
 conditionisWHEN_IN_FOCUSED_WINDOWandmapis not aComponentInputMap, anIllegalArgumentExceptionwill be thrown. Similarly, ifconditionis not one of the values listed, anIllegalArgumentExceptionwill be thrown.- Parameters:
- condition- one of the values listed above
- map- the- InputMapto use for the given condition
- Throws:
- IllegalArgumentException- if- conditionis- WHEN_IN_FOCUSED_WINDOWand- mapis not an instance of- ComponentInputMap; or if- conditionis not one of the legal values specified above
- Since:
- 1.3
 
- 
getInputMapReturns theInputMapthat is used duringcondition.- Parameters:
- condition- one of WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
- Returns:
- the InputMapfor the specifiedcondition
- Since:
- 1.3
 
- 
getInputMapReturns theInputMapthat is used when the component has focus. This is convenience method forgetInputMap(WHEN_FOCUSED).- Returns:
- the InputMapused when the component has focus
- Since:
- 1.3
 
- 
setActionMapSets theActionMaptoam. 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.- Parameters:
- am- the new- ActionMap
- Since:
- 1.3
 
- 
getActionMapReturns theActionMapused to determine whatActionto fire for particularKeyStrokebinding. The returnedActionMap, unless otherwise set, will have theActionMapfrom the UI set as the parent.- Returns:
- the ActionMapcontaining the key/action bindings
- Since:
- 1.3
 
- 
getBaselinepublic int getBaseline(int width, int height) Returns the baseline. The baseline is measured from the top of the component. This method is primarily meant forLayoutManagers to align components along their baseline. A return value less than 0 indicates this component does not have a reasonable baseline and thatLayoutManagers should not align this component on its baseline.This method calls into the ComponentUImethod of the same name. If this component does not have aComponentUI-1 will be returned. If a value >= 0 is returned, then the component has a valid baseline for any size >= the minimum size andgetBaselineResizeBehaviorcan be used to determine how the baseline changes with size.- Overrides:
- getBaselinein class- Component
- Parameters:
- width- the width to get the baseline for
- height- the height to get the baseline for
- Returns:
- the baseline or < 0 indicating there is no reasonable baseline
- Throws:
- IllegalArgumentException- if width or height is < 0
- Since:
- 1.6
- See Also:
 
- 
getBaselineResizeBehaviorReturns an enum indicating how the baseline of the component changes as the size changes. This method is primarily meant for layout managers and GUI builders.This method calls into the ComponentUImethod of the same name. If this component does not have aComponentUIBaselineResizeBehavior.OTHERwill be returned. Subclasses should never returnnull; if the baseline can not be calculated returnBaselineResizeBehavior.OTHER. Callers should first ask for the baseline usinggetBaselineand if a value >= 0 is returned use this method. It is acceptable for this method to return a value other thanBaselineResizeBehavior.OTHEReven ifgetBaselinereturns a value less than 0.- Overrides:
- getBaselineResizeBehaviorin class- Component
- Returns:
- an enum indicating how the baseline changes as the component size changes
- Since:
- 1.6
- See Also:
 
- 
requestDefaultFocusDeprecated.As of 1.4, replaced byFocusTraversalPolicy.getDefaultComponent(Container).requestFocus()In release 1.4, the focus subsystem was rearchitected. For more information, see How to Use the Focus Subsystem, a section in The Java Tutorial.Requests focus on this JComponent'sFocusTraversalPolicy's defaultComponent. If thisJComponentis a focus cycle root, then itsFocusTraversalPolicyis used. Otherwise, theFocusTraversalPolicyof thisJComponent's focus-cycle-root ancestor is used.- Returns:
- true if this component can request to get the input focus, false if it can not
- See Also:
 
- 
setVisibleMakes the component visible or invisible. OverridesComponent.setVisible.- Overrides:
- setVisiblein class- Component
- Parameters:
- aFlag- true to make the component visible; false to make it invisible
- See Also:
 
- 
setEnabled@BeanProperty(expert=true, preferred=true, visualUpdate=true, description="The enabled state of the component.") public void setEnabled(boolean enabled) 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.Note: Disabling a component does not disable its children. Note: Disabling a lightweight component does not prevent it from receiving MouseEvents. - Overrides:
- setEnabledin class- Component
- Parameters:
- enabled- true if this component should be enabled, false otherwise
- See Also:
 
- 
setForeground@BeanProperty(preferred=true, visualUpdate=true, description="The foreground color of the component.") public void setForeground(Color fg) Sets the foreground color of this component. It is up to the look and feel to honor this property, some may choose to ignore it.- Overrides:
- setForegroundin class- Component
- Parameters:
- fg- the desired foreground- Color
- See Also:
 
- 
setBackground@BeanProperty(preferred=true, visualUpdate=true, description="The background color of the component.") public void setBackground(Color bg) Sets the background color of this component. The background color is used only if the component is opaque, and only by subclasses ofJComponentorComponentUIimplementations. Direct subclasses ofJComponentmust overridepaintComponentto honor this property.It is up to the look and feel to honor this property, some may choose to ignore it. - Overrides:
- setBackgroundin class- Component
- Parameters:
- bg- the desired background- Color
- See Also:
 
- 
setFont@BeanProperty(preferred=true, visualUpdate=true, description="The font for the component.") public void setFont(Font font) Sets the font for this component.
- 
getDefaultLocaleReturns the default locale used to initialize each JComponent's locale property upon creation. The default locale has "AppContext" scope so that applets (and potentially multiple lightweight applications running in a single VM) can have their own setting. An applet can safely alter its default locale because it will have no affect on other applets (or the browser).- Returns:
- the default Locale.
- Since:
- 1.4
- See Also:
 
- 
setDefaultLocaleSets the default locale used to initialize each JComponent's locale property upon creation. The initial value is the VM's default locale. The default locale has "AppContext" scope so that applets (and potentially multiple lightweight applications running in a single VM) can have their own setting. An applet can safely alter its default locale because it will have no affect on other applets (or the browser). Passingnullwill reset the current locale back to VM's default locale.- Parameters:
- l- the desired default- Localefor new components.
- Since:
- 1.4
- See Also:
 
- 
processComponentKeyEventProcesses any key events that the component itself recognizes. This is called after the focus manager and any interested listeners have been given a chance to steal away the event. This method is called only if the event has not yet been consumed. This method is called prior to the keyboard UI logic.This method is implemented to do nothing. Subclasses would normally override this method if they process some key events themselves. If the event is processed, it should be consumed. - Parameters:
- e- the event to be processed
 
- 
processKeyEventOverridesprocessKeyEventto process events.- Overrides:
- processKeyEventin class- Component
- Parameters:
- e- the key event
- See Also:
 
- 
processKeyBindingInvoked to process the key bindings forksas the result of theKeyEvente. This obtains the appropriateInputMap, gets the binding, gets the action from theActionMap, and then (if the action is found and the component is enabled) invokesnotifyActionto notify the action.- Parameters:
- ks- the- KeyStrokequeried
- e- the- KeyEvent
- condition- one of the following values:- JComponent.WHEN_FOCUSED
- JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
- JComponent.WHEN_IN_FOCUSED_WINDOW
 
- pressed- true if the key is pressed
- Returns:
- true if there was a binding to an action, and the action was enabled
- Since:
- 1.3
 
- 
setToolTipText@BeanProperty(bound=false, preferred=true, description="The text to display in a tool tip.") public void setToolTipText(String text) Registers the text to display in a tool tip. The text displays when the cursor lingers over the component.See How to Use Tool Tips in The Java Tutorial for further documentation. - Parameters:
- text- the string to display; if the text is- null, the tool tip is turned off for this component
- See Also:
 
- 
getToolTipTextReturns the tooltip string that has been set withsetToolTipText.- Returns:
- the text of the tool tip
- See Also:
 
- 
getToolTipTextReturns the string to be used as the tooltip for event. By default this returns any string set usingsetToolTipText. If a component provides more extensive API to support differing tooltips at different locations, this method should be overridden.- Parameters:
- event- the- MouseEventthat initiated the- ToolTipdisplay
- Returns:
- a string containing the tooltip
 
- 
getToolTipLocationReturns the tooltip location in this component's coordinate system. Ifnullis returned, Swing will choose a location. The default implementation returnsnull.- Parameters:
- event- the- MouseEventthat caused the- ToolTipManagerto show the tooltip
- Returns:
- always returns null
 
- 
getPopupLocationReturns the preferred location to display the popup menu in this component's coordinate system. It is up to the look and feel to honor this property, some may choose to ignore it. Ifnull, the look and feel will choose a suitable location.- Parameters:
- event- the- MouseEventthat triggered the popup to be shown, or- nullif the popup is not being shown as the result of a mouse event
- Returns:
- location to display the JPopupMenu, ornull
- Since:
- 1.5
 
- 
createToolTipReturns the instance ofJToolTipthat 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.- Returns:
- the JToolTipused to display this toolTip
 
- 
scrollRectToVisibleForwards thescrollRectToVisible()message to theJComponent's parent. Components that can service the request, such asJViewport, override this method and perform the scrolling.- Parameters:
- aRect- the visible- Rectangle
- See Also:
 
- 
setAutoscrolls@BeanProperty(bound=false, expert=true, description="Determines if this component automatically scrolls its contents when dragged.") public void setAutoscrolls(boolean autoscrolls) Sets theautoscrollsproperty. Iftruemouse dragged events will be synthetically generated when the mouse is dragged outside 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 when the 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(JTable,JList,JTree,JTextArea, andJEditorPane) already handle mouse dragged events in this way. To enable autoscrolling in any other component, add a mouse motion listener that callsscrollRectToVisible. For example, given aJPanel,myPanel: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.- Parameters:
- autoscrolls- 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 Also:
 
- 
getAutoscrollspublic boolean getAutoscrolls()Gets theautoscrollsproperty.- Returns:
- the value of the autoscrollsproperty
- See Also:
 
- 
setTransferHandler@BeanProperty(hidden=true, description="Mechanism for transfer of data to and from the component") public void setTransferHandler(TransferHandler newHandler) Sets theTransferHandler, which provides support for transfer of data into and out of this component via cut/copy/paste and drag and drop. This may benullif the component does not support data transfer operations.If the new TransferHandleris notnull, this method also installs a newDropTargeton the component to activate drop handling through theTransferHandlerand activate any built-in support (such as calculating and displaying potential drop locations). If you do not wish for this component to respond in any way to drops, you can disable drop support entirely either by removing the drop target (setDropTarget(null)) or by de-activating it (getDropTaget().setActive(false)).If the new TransferHandlerisnull, this method removes the drop target.Under two circumstances, this method does not modify the drop target: First, if the existing drop target on this component was explicitly set by the developer to a non-nullvalue. Second, if the system propertysuppressSwingDropSupportistrue. The default value for the system property isfalse.Please see How to Use Drag and Drop and Data Transfer, a section in The Java Tutorial, for more information. - Parameters:
- newHandler- the new- TransferHandler
- Since:
- 1.4
- See Also:
 
- 
getTransferHandlerGets thetransferHandlerproperty.- Returns:
- the value of the transferHandlerproperty
- Since:
- 1.4
- See Also:
 
- 
processMouseEventProcesses mouse events occurring on this component by dispatching them to any registeredMouseListenerobjects, refer toComponent.processMouseEvent(MouseEvent)for a complete description of this method.- Overrides:
- processMouseEventin class- Component
- Parameters:
- e- the mouse event
- Since:
- 1.5
- See Also:
 
- 
processMouseMotionEventProcesses mouse motion events, such as MouseEvent.MOUSE_DRAGGED.- Overrides:
- processMouseMotionEventin class- Component
- Parameters:
- e- the- MouseEvent
- See Also:
 
- 
enableDeprecated.As of JDK version 1.1, replaced byjava.awt.Component.setEnabled(boolean).
- 
disableDeprecated.As of JDK version 1.1, replaced byjava.awt.Component.setEnabled(boolean).
- 
getClientPropertyReturns the value of the property with the specified key. Only properties added withputClientPropertywill return a non-nullvalue.- Parameters:
- key- the being queried
- Returns:
- the value of this property or null
- See Also:
 
- 
putClientPropertyAdds an arbitrary key/value "client property" to this component.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.- Parameters:
- key- the new client property key
- value- the new client property value; if- nullthis method will remove the property
- See Also:
 
- 
setFocusTraversalKeysSets the focus traversal keys for a given traversal operation for this Component. Refer toComponent.setFocusTraversalKeys(int, java.util.Set<? extends java.awt.AWTKeyStroke>)for a complete description of this method.This method may throw a ClassCastExceptionif anyObjectinkeystrokesis not anAWTKeyStroke.- Overrides:
- setFocusTraversalKeysin class- Container
- Parameters:
- id- one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
- keystrokes- the Set of AWTKeyStroke for the specified operation
- Throws:
- IllegalArgumentException- if id is not one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes contains null, or if any keystroke represents a KEY_TYPED event, or if any keystroke already maps to another focus traversal operation for this Component
- Since:
- 1.5
- See Also:
 
- 
isLightweightComponentReturns true if this component is lightweight, that is, if it doesn't have a native window system peer.- Parameters:
- c- the- Componentto be checked
- Returns:
- true if this component is lightweight
 
- 
reshapeDeprecated.As of JDK 5, replaced byComponent.setBounds(int, int, int, int).Moves and resizes this component. Description copied from class:ComponentReshapes the bounding rectangle for this component.
- 
getBoundsStores the bounds of this component into "return value"rvand returnsrv. Ifrvisnulla newRectangleis allocated. This version ofgetBoundsis useful if the caller wants to avoid allocating a newRectangleobject on the heap.
- 
getSizeStores the width/height of this component into "return value"rvand returnsrv. Ifrvisnulla newDimensionobject is allocated. This version ofgetSizeis useful if the caller wants to avoid allocating a newDimensionobject on the heap.
- 
getLocationStores the x,y origin of this component into "return value"rvand returnsrv. Ifrvisnulla newPointis allocated. This version ofgetLocationis useful if the caller wants to avoid allocating a newPointobject on the heap.- Overrides:
- getLocationin class- Component
- Parameters:
- rv- the return value, modified to the component's location
- Returns:
- rv
 
- 
getXReturns the current x coordinate of the component's origin. This method is preferable to writingcomponent.getBounds().x, orcomponent.getLocation().xbecause it doesn't cause any heap allocations.
- 
getYReturns the current y coordinate of the component's origin. This method is preferable to writingcomponent.getBounds().y, orcomponent.getLocation().ybecause it doesn't cause any heap allocations.
- 
getWidthReturns the current width of this component. This method is preferable to writingcomponent.getBounds().width, orcomponent.getSize().widthbecause it doesn't cause any heap allocations.
- 
getHeightReturns the current height of this component. This method is preferable to writingcomponent.getBounds().height, orcomponent.getSize().heightbecause it doesn't cause any heap allocations.
- 
isOpaquepublic boolean isOpaque()Returns true if this component is completely opaque.An opaque component paints every pixel within its rectangular bounds. A non-opaque component paints only a subset of its pixels or none at all, allowing the pixels underneath it to "show through". Therefore, a component that does not fully paint its pixels provides a degree of transparency. Subclasses that guarantee to always completely paint their contents should override this method and return true. 
- 
setOpaque@BeanProperty(expert=true, description="The component\'s opacity") public void setOpaque(boolean isOpaque) 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.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.- Parameters:
- isOpaque- true if this component should be opaque
- See Also:
 
- 
computeVisibleRectReturns theComponent's "visible rect rectangle" - the intersection of the visible rectangles for this component and all of its ancestors. The return value is stored invisibleRect.- Parameters:
- visibleRect- a- Rectanglecomputed as the intersection of all visible rectangles for this component and all of its ancestors -- this is the return value for this method
- See Also:
 
- 
getVisibleRectReturns theComponent's "visible rectangle" - the intersection of this component's visible rectangle,new Rectangle(0, 0, getWidth(), getHeight()), and all of its ancestors' visible rectangles.- Returns:
- the visible rectangle
 
- 
firePropertyChangeSupport for reporting bound property changes for boolean properties. This method can be called when a bound property has changed and it will send the appropriate PropertyChangeEvent to any registered PropertyChangeListeners.- Overrides:
- firePropertyChangein class- Component
- Parameters:
- propertyName- the property whose value has changed
- oldValue- the property's previous value
- newValue- the property's new value
 
- 
firePropertyChangeSupport for reporting bound property changes for integer properties. This method can be called when a bound property has changed and it will send the appropriate PropertyChangeEvent to any registered PropertyChangeListeners.- Overrides:
- firePropertyChangein class- Component
- Parameters:
- propertyName- the property whose value has changed
- oldValue- the property's previous value
- newValue- the property's new value
 
- 
fireVetoableChangeprotected void fireVetoableChange(String propertyName, Object oldValue, Object newValue) throws PropertyVetoException Supports reporting constrained property changes. This method can be called when a constrained property has changed and it will send the appropriatePropertyChangeEventto any registeredVetoableChangeListeners.- Parameters:
- propertyName- the name of the property that was listened on
- oldValue- the old value of the property
- newValue- the new value of the property
- Throws:
- PropertyVetoException- when the attempt to set the property is vetoed by the component
 
- 
addVetoableChangeListenerAdds aVetoableChangeListenerto the listener list. The listener is registered for all properties.- Parameters:
- listener- the- VetoableChangeListenerto be added
 
- 
removeVetoableChangeListenerRemoves aVetoableChangeListenerfrom the listener list. This removes aVetoableChangeListenerthat was registered for all properties.- Parameters:
- listener- the- VetoableChangeListenerto be removed
 
- 
getVetoableChangeListenersReturns an array of all the vetoable change listeners registered on this component.- Returns:
- all of the component's VetoableChangeListeners or an empty array if no vetoable change listeners are currently registered
- Since:
- 1.4
- See Also:
 
- 
getTopLevelAncestorReturns the top-level ancestor of this component (either the containingWindoworApplet), ornullif this component has not been added to any container.- Returns:
- the top-level Containerthat this component is in, ornullif not in any container
 
- 
addAncestorListenerRegisterslistenerso 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.- Parameters:
- listener- the- AncestorListenerto register
- See Also:
 
- 
removeAncestorListenerUnregisterslistenerso that it will no longer receiveAncestorEvents.- Parameters:
- listener- the- AncestorListenerto be removed
- See Also:
 
- 
getAncestorListenersReturns an array of all the ancestor listeners registered on this component.- Returns:
- all of the component's AncestorListeners or an empty array if no ancestor listeners are currently registered
- Since:
- 1.4
- See Also:
 
- 
getListenersReturns an array of all the objects currently registered asFooListeners upon thisJComponent.FooListeners are registered using theaddFooListenermethod.You can specify the listenerTypeargument with a class literal, such asFooListener.class. For example, you can query aJComponentcfor its mouse listeners with the following code:MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class)); If no such listeners exist, this method returns an empty array.- Overrides:
- getListenersin class- Container
- Type Parameters:
- T- the type of the listeners
- Parameters:
- listenerType- the type of listeners requested; this parameter should specify an interface that descends from- java.util.EventListener
- Returns:
- an array of all objects registered as
          FooListeners on this component, or an empty array if no such listeners have been added
- Throws:
- ClassCastException- if- listenerTypedoesn't specify a class or interface that implements- java.util.EventListener
- Since:
- 1.3
- See Also:
 
- 
addNotifypublic void addNotify()Notifies this component that it now has a parent component. When this method is invoked, the chain of parent components is set up withKeyboardActionevent listeners. This method is called by the toolkit internally and should not be called directly by programs.
- 
removeNotifypublic void removeNotify()Notifies this component that it no longer has a parent component. When this method is invoked, anyKeyboardActions set up in the chain of parent components are removed. This method is called by the toolkit internally and should not be called directly by programs.- Overrides:
- removeNotifyin class- Container
- See Also:
 
- 
repaintpublic void repaint(long tm, int x, int y, int width, int height) 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.
- 
repaintAdds 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.- Parameters:
- r- a- Rectanglecontaining the dirty region
- See Also:
 
- 
revalidatepublic void revalidate()Supports deferred automatic layout.Calls invalidateand then adds this component'svalidateRootto 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 default,JRootPane,JScrollPane, andJTextFieldreturn 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.- Overrides:
- revalidatein class- Component
- See Also:
 
- 
isValidateRootpublic boolean isValidateRoot()If this method returns true,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.- Overrides:
- isValidateRootin class- Container
- Returns:
- always returns false
- See Also:
 
- 
isOptimizedDrawingEnabledReturns 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.JComponentsubclasses that can't make this guarantee, such asJLayeredPane, should override this method to return false.- Returns:
- always returns true
 
- 
isPaintingOriginprotected boolean isPaintingOrigin()Returnstrueif a paint triggered on a child component should cause painting to originate from this Component, or one of its ancestors.Calling repaint(long, int, int, int, int)orpaintImmediately(int, int, int, int)on a Swing component will result in calling thepaintImmediately(int, int, int, int)method of the first ancestor whichisPaintingOrigin()returnstrue, if there are any.JComponentsubclasses that need to be painted when any of their children are repainted should override this method to returntrue.- Returns:
- always returns false
- See Also:
 
- 
paintImmediatelypublic void paintImmediately(int x, int y, int w, int h) Paints the specified region in this component and all of its descendants that overlap the region, immediately.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. This method is to be overridden when the dirty region needs to be changed for components that are painting origins. - Parameters:
- x- the x value of the region to be painted
- y- the y value of the region to be painted
- w- the width of the region to be painted
- h- the height of the region to be painted
- See Also:
 
- 
paintImmediatelyPaints the specified region now.- Parameters:
- r- a- Rectanglecontaining the region to be painted
 
- 
setDoubleBufferedpublic void setDoubleBuffered(boolean aFlag) Sets whether this 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. If aComponentis buffered and one of its ancestor is also buffered, the ancestor buffer will be used.- Parameters:
- aFlag- if true, set this component to be double buffered
 
- 
isDoubleBufferedpublic boolean isDoubleBuffered()Returns whether this component should use a buffer to paint.- Overrides:
- isDoubleBufferedin class- Component
- Returns:
- true if this component is double buffered, otherwise false
 
- 
getRootPaneReturns theJRootPaneancestor for this component.- Returns:
- the JRootPanethat contains this component, ornullif noJRootPaneis found
 
- 
paramStringReturns a string representation of thisJComponent. 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.- Overrides:
- paramStringin class- Container
- Returns:
- a string representation of this JComponent
 
- 
hideDeprecated.
 
- 
java.awt.Component.setEnabled(boolean).