Class SwingUtilities
- All Implemented Interfaces:
SwingConstants
- Since:
- 1.2
-
Field Summary
Fields declared in interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
-
Method Summary
Modifier and TypeMethodDescriptionstatic Rectangle
Stores the position and size of the inner painting area of the specified component inr
and returnsr
.static Rectangle[]
computeDifference
(Rectangle rectA, Rectangle rectB) Convenience returning an array of rect representing the regions withinrectA
that do not overlap withrectB
.static Rectangle
computeIntersection
(int x, int y, int width, int height, Rectangle dest) Convenience to calculate the intersection of two rectangles without allocating a new rectangle.static int
computeStringWidth
(FontMetrics fm, String str) Compute the width of the string using a font with the specified "metrics" (sizes).static Rectangle
computeUnion
(int x, int y, int width, int height, Rectangle dest) Convenience method that calculates the union of two rectangles without allocating a new rectangle.static MouseEvent
convertMouseEvent
(Component source, MouseEvent sourceEvent, Component destination) Returns a MouseEvent similar tosourceEvent
except that its x and y members have been converted todestination
's coordinate system.static Point
convertPoint
(Component source, int x, int y, Component destination) Convert the point(x,y)
insource
coordinate system todestination
coordinate system.static Point
convertPoint
(Component source, Point aPoint, Component destination) Convert aaPoint
insource
coordinate system todestination
coordinate system.static void
Convert a point from a screen coordinates to a component's coordinate systemstatic void
Convert a point from a component's coordinate system to screen coordinates.static Rectangle
convertRectangle
(Component source, Rectangle aRectangle, Component destination) Convert the rectangleaRectangle
insource
coordinate system todestination
coordinate system.static Component
Deprecated.static Accessible
getAccessibleAt
(Component c, Point p) Returns theAccessible
child contained at the local coordinatePoint
, if one exists.static Accessible
getAccessibleChild
(Component c, int i) Return the nth Accessible child of the object.static int
Returns the number of accessible children in the object.static int
Get the index of this object in its accessible parent.static AccessibleStateSet
Get the state of this object.static Container
getAncestorNamed
(String name, Component comp) Convenience method for searching abovecomp
in the component hierarchy and returns the first object ofname
it finds.static Container
getAncestorOfClass
(Class<?> c, Component comp) Convenience method for searching abovecomp
in the component hierarchy and returns the first object of classc
it finds.static Component
getDeepestComponentAt
(Component parent, int x, int y) Returns the deepest visible descendent Component ofparent
that contains the locationx
,y
.static Rectangle
getLocalBounds
(Component aComponent) Return the rectangle (0,0,bounds.width,bounds.height) for the componentaComponent
static Component
Returns the root component for the current component tree.static JRootPane
If c is a JRootPane descendant return its JRootPane ancestor.static ActionMap
getUIActionMap
(JComponent component) Returns the ActionMap provided by the UI in componentcomponent
.static InputMap
getUIInputMap
(JComponent component, int condition) Returns the InputMap provided by the UI for conditioncondition
in componentcomponent
.static Container
getUnwrappedParent
(Component component) Returns the first ancestor of thecomponent
which is not an instance ofJLayer
.static Component
getUnwrappedView
(JViewport viewport) Returns the firstJViewport
's descendant which is not an instance ofJLayer
.static Window
Returns the firstWindow
ancestor ofc
, ornull
ifc
is not contained inside aWindow
.static void
invokeAndWait
(Runnable doRun) CausesdoRun.run()
to be executed synchronously on the AWT event dispatching thread.static void
invokeLater
(Runnable doRun) Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread.static boolean
Returntrue
if a componenta
descends from a componentb
static boolean
Returns true if the current thread is an AWT event dispatching thread.static boolean
isLeftMouseButton
(MouseEvent anEvent) Returns true if the mouse event specifies the left mouse button.static boolean
isMiddleMouseButton
(MouseEvent anEvent) Returns true if the mouse event specifies the middle mouse button.static final boolean
Returntrue
ifa
containsb
static boolean
isRightMouseButton
(MouseEvent anEvent) Returns true if the mouse event specifies the right mouse button.static String
layoutCompoundLabel
(FontMetrics fm, String text, Icon icon, int verticalAlignment, int horizontalAlignment, int verticalTextPosition, int horizontalTextPosition, Rectangle viewR, Rectangle iconR, Rectangle textR, int textIconGap) Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly clipped version of the compound labels string.static String
layoutCompoundLabel
(JComponent c, FontMetrics fm, String text, Icon icon, int verticalAlignment, int horizontalAlignment, int verticalTextPosition, int horizontalTextPosition, Rectangle viewR, Rectangle iconR, Rectangle textR, int textIconGap) Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly clipped version of the compound labels string.static boolean
notifyAction
(Action action, KeyStroke ks, KeyEvent event, Object sender, int modifiers) InvokesactionPerformed
onaction
ifaction
is non-null
and accepts the sender object.static void
paintComponent
(Graphics g, Component c, Container p, int x, int y, int w, int h) Paints a component to the specifiedGraphics
.static void
paintComponent
(Graphics g, Component c, Container p, Rectangle r) Paints a component to the specifiedGraphics
.static boolean
processKeyBindings
(KeyEvent event) Process the key bindings for theComponent
associated withevent
.static void
replaceUIActionMap
(JComponent component, ActionMap uiActionMap) Convenience method to change the UI ActionMap forcomponent
touiActionMap
.static void
replaceUIInputMap
(JComponent component, int type, InputMap uiInputMap) Convenience method to change the UI InputMap forcomponent
touiInputMap
.static void
A simple minded look and feel change: ask each node in the tree toupdateUI()
-- that is, to initialize its UI property with the current look and feel.static Window
Returns the firstWindow
ancestor ofc
, ornull
ifc
is not contained inside aWindow
.
-
Method Details
-
isRectangleContainingRectangle
-
getLocalBounds
-
getWindowAncestor
-
convertPoint
Convert aaPoint
insource
coordinate system todestination
coordinate system. Ifsource
isnull
,aPoint
is assumed to be indestination
's root component coordinate system. Ifdestination
isnull
,aPoint
will be converted tosource
's root component coordinate system. If bothsource
anddestination
arenull
, returnaPoint
without any conversion.- Parameters:
source
- the source componentaPoint
- the pointdestination
- the destination component- Returns:
- the converted coordinate
-
convertPoint
Convert the point(x,y)
insource
coordinate system todestination
coordinate system. Ifsource
isnull
,(x,y)
is assumed to be indestination
's root component coordinate system. Ifdestination
isnull
,(x,y)
will be converted tosource
's root component coordinate system. If bothsource
anddestination
arenull
, return(x,y)
without any conversion.- Parameters:
source
- the source componentx
- the x-coordinate of the pointy
- the y-coordinate of the pointdestination
- the destination component- Returns:
- the converted coordinate
-
convertRectangle
public static Rectangle convertRectangle(Component source, Rectangle aRectangle, Component destination) Convert the rectangleaRectangle
insource
coordinate system todestination
coordinate system. Ifsource
isnull
,aRectangle
is assumed to be indestination
's root component coordinate system. Ifdestination
isnull
,aRectangle
will be converted tosource
's root component coordinate system. If bothsource
anddestination
arenull
, returnaRectangle
without any conversion.- Parameters:
source
- the source componentaRectangle
- a rectangledestination
- the destination component- Returns:
- the converted rectangle
-
getAncestorOfClass
Convenience method for searching abovecomp
in the component hierarchy and returns the first object of classc
it finds. Can returnnull
, if a classc
cannot be found.- Parameters:
c
- the class of a componentcomp
- the component- Returns:
- the ancestor of the
comp
, ornull
ifc
cannot be found.
-
getAncestorNamed
Convenience method for searching abovecomp
in the component hierarchy and returns the first object ofname
it finds. Can returnnull
, ifname
cannot be found.- Parameters:
name
- the name of a componentcomp
- the component- Returns:
- the ancestor of the
comp
, ornull
ifname
cannot be found.
-
getDeepestComponentAt
Returns the deepest visible descendent Component ofparent
that contains the locationx
,y
. Ifparent
does not contain the specified location, thennull
is returned. Ifparent
is not a container, or none ofparent
's visible descendents contain the specified location,parent
is returned.- Parameters:
parent
- the root component to begin the searchx
- the x target locationy
- the y target location- Returns:
- the deepest component
-
convertMouseEvent
public static MouseEvent convertMouseEvent(Component source, MouseEvent sourceEvent, Component destination) Returns a MouseEvent similar tosourceEvent
except that its x and y members have been converted todestination
's coordinate system. Ifsource
isnull
,sourceEvent
x and y members are assumed to be intodestination
's root component coordinate system. Ifdestination
isnull
, the returned MouseEvent will be insource
's coordinate system.sourceEvent
will not be changed. A new event is returned. thesource
field of the returned event will be set todestination
if destination is non-null
use the translateMouseEvent() method to translate a mouse event from one component to another without changing the source.- Parameters:
source
- the source componentsourceEvent
- the source mouse eventdestination
- the destination component- Returns:
- the new mouse event
-
convertPointToScreen
-
convertPointFromScreen
-
windowForComponent
Returns the firstWindow
ancestor ofc
, ornull
ifc
is not contained inside aWindow
.Note: This method provides the same functionality as
getWindowAncestor
.- Parameters:
c
-Component
to getWindow
ancestor of.- Returns:
- the first
Window
ancestor ofc
, ornull
ifc
is not contained inside aWindow
.
-
isDescendingFrom
-
computeIntersection
Convenience to calculate the intersection of two rectangles without allocating a new rectangle. If the two rectangles don't intersect, then the returned rectangle begins at (0,0) and has zero width and height.- Parameters:
x
- the X coordinate of the first rectangle's top-left pointy
- the Y coordinate of the first rectangle's top-left pointwidth
- the width of the first rectangleheight
- the height of the first rectangledest
- the second rectangle- Returns:
dest
, modified to specify the intersection
-
computeUnion
Convenience method that calculates the union of two rectangles without allocating a new rectangle.- Parameters:
x
- the x-coordinate of the first rectangley
- the y-coordinate of the first rectanglewidth
- the width of the first rectangleheight
- the height of the first rectangledest
- the coordinates of the second rectangle; the union of the two rectangles is returned in this rectangle- Returns:
- the
dest
Rectangle
-
computeDifference
Convenience returning an array of rect representing the regions withinrectA
that do not overlap withrectB
. If the two Rects do not overlap, returns an empty array- Parameters:
rectA
- the first rectanglerectB
- the second rectangle- Returns:
- an array of rectangles representing the regions within
rectA
that do not overlap withrectB
.
-
isLeftMouseButton
Returns true if the mouse event specifies the left mouse button.- Parameters:
anEvent
- a MouseEvent object- Returns:
- true if the left mouse button was active
-
isMiddleMouseButton
Returns true if the mouse event specifies the middle mouse button.- Parameters:
anEvent
- a MouseEvent object- Returns:
- true if the middle mouse button was active
-
isRightMouseButton
Returns true if the mouse event specifies the right mouse button.- Parameters:
anEvent
- a MouseEvent object- Returns:
- true if the right mouse button was active
-
computeStringWidth
Compute the width of the string using a font with the specified "metrics" (sizes).- Parameters:
fm
- a FontMetrics object to compute withstr
- the String to compute- Returns:
- an int containing the string width
-
layoutCompoundLabel
public static String layoutCompoundLabel(JComponent c, FontMetrics fm, String text, Icon icon, int verticalAlignment, int horizontalAlignment, int verticalTextPosition, int horizontalTextPosition, Rectangle viewR, Rectangle iconR, Rectangle textR, int textIconGap) Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly clipped version of the compound labels string. Locations are computed relative to the viewR rectangle. The JComponents orientation (LEADING/TRAILING) will also be taken into account and translated into LEFT/RIGHT values accordingly.- Parameters:
c
- the componentfm
- the instance ofFontMetrics
text
- the texticon
- the iconverticalAlignment
- the vertical alignmenthorizontalAlignment
- the horizontal alignmentverticalTextPosition
- the vertical text positionhorizontalTextPosition
- the horizontal text positionviewR
- the available rectangleiconR
- the rectangle for the icontextR
- the rectangle for the texttextIconGap
- the gap between text and icon- Returns:
- the possibly clipped version of the compound labels string
-
layoutCompoundLabel
public static String layoutCompoundLabel(FontMetrics fm, String text, Icon icon, int verticalAlignment, int horizontalAlignment, int verticalTextPosition, int horizontalTextPosition, Rectangle viewR, Rectangle iconR, Rectangle textR, int textIconGap) Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly clipped version of the compound labels string. Locations are computed relative to the viewR rectangle. This layoutCompoundLabel() does not know how to handle LEADING/TRAILING values in horizontalTextPosition (they will default to RIGHT) and in horizontalAlignment (they will default to CENTER). Use the other version of layoutCompoundLabel() instead.- Parameters:
fm
- the instance ofFontMetrics
text
- the texticon
- the iconverticalAlignment
- the vertical alignmenthorizontalAlignment
- the horizontal alignmentverticalTextPosition
- the vertical text positionhorizontalTextPosition
- the horizontal text positionviewR
- the available rectangleiconR
- the rectangle for the icontextR
- the rectangle for the texttextIconGap
- the gap between text and icon- Returns:
- the possibly clipped version of the compound labels string
-
paintComponent
Paints a component to the specifiedGraphics
. This method is primarily useful to renderComponent
s that don't exist as part of the visible containment hierarchy, but are used for rendering. For example, if you are doing your own rendering and want to render some text (or even HTML), you could make use ofJLabel
's text rendering support and have it paint directly by way of this method, without adding the label to the visible containment hierarchy.This method makes use of
CellRendererPane
to handle the actual painting, and is only recommended if you use one component for rendering. If you make use of multiple components to handle the rendering, asJTable
does, useCellRendererPane
directly. Otherwise, as described below, you could end up with aCellRendererPane
perComponent
.If
c
's parent is not aCellRendererPane
, a newCellRendererPane
is created,c
is added to it, and theCellRendererPane
is added top
. Ifc
's parent is aCellRendererPane
and theCellRendererPane
s parent is notp
, it is added top
.The component should either descend from
JComponent
or be another kind of lightweight component. A lightweight component is one whose "lightweight" property (returned by theComponent
isLightweight
method) is true. If the Component is not lightweight, bad things map happen: crashes, exceptions, painting problems...- Parameters:
g
- theGraphics
object to draw onc
- theComponent
to drawp
- the intermediateContainer
x
- an int specifying the left side of the area draw in, in pixels, measured from the left edge of the graphics contexty
- an int specifying the top of the area to draw in, in pixels measured down from the top edge of the graphics contextw
- an int specifying the width of the area draw in, in pixelsh
- an int specifying the height of the area draw in, in pixels- See Also:
-
paintComponent
Paints a component to the specifiedGraphics
. This is a cover method forpaintComponent(Graphics,Component,Container,int,int,int,int)
. Refer to it for more information.- Parameters:
g
- theGraphics
object to draw onc
- theComponent
to drawp
- the intermediateContainer
r
- theRectangle
to draw in- See Also:
-
updateComponentTreeUI
A simple minded look and feel change: ask each node in the tree toupdateUI()
-- that is, to initialize its UI property with the current look and feel.- Parameters:
c
- the component
-
invokeLater
Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI. In the following example theinvokeLater
call queues theRunnable
objectdoHelloWorld
on the event dispatching thread and then prints a message.Runnable doHelloWorld = new Runnable() { public void run() { System.out.println("Hello World on " + Thread.currentThread()); } }; SwingUtilities.invokeLater(doHelloWorld); System.out.println("This might well be displayed before the other message.");
If invokeLater is called from the event dispatching thread -- for example, from a JButton's ActionListener -- the doRun.run() will still be deferred until all pending events have been processed. Note that if the doRun.run() throws an uncaught exception the event dispatching thread will unwind (not the current thread).Additional documentation and examples for this method can be found in Concurrency in Swing.
As of 1.3 this method is just a cover for
java.awt.EventQueue.invokeLater()
.Unlike the rest of Swing, this method can be invoked from any thread.
- Parameters:
doRun
- the instance ofRunnable
- See Also:
-
invokeAndWait
public static void invokeAndWait(Runnable doRun) throws InterruptedException, InvocationTargetException CausesdoRun.run()
to be executed synchronously on the AWT event dispatching thread. This call blocks until all pending AWT events have been processed and (then)doRun.run()
returns. This method should be used when an application thread needs to update the GUI. It shouldn't be called from the event dispatching thread. Here's an example that creates a new application thread that usesinvokeAndWait
to print a string from the event dispatching thread and then, when that's finished, print a string from the application thread.final Runnable doHelloWorld = new Runnable() { public void run() { System.out.println("Hello World on " + Thread.currentThread()); } }; Thread appThread = new Thread() { public void run() { try { SwingUtilities.invokeAndWait(doHelloWorld); } catch (Exception e) { e.printStackTrace(); } System.out.println("Finished on " + Thread.currentThread()); } }; appThread.start();
Note that if theRunnable.run
method throws an uncaught exception (on the event dispatching thread) it's caught and rethrown, as anInvocationTargetException
, on the caller's thread.Additional documentation and examples for this method can be found in Concurrency in Swing.
As of 1.3 this method is just a cover for
java.awt.EventQueue.invokeAndWait()
.- Parameters:
doRun
- the instance ofRunnable
- Throws:
InterruptedException
- if we're interrupted while waiting for the event dispatching thread to finish executingdoRun.run()
InvocationTargetException
- if an exception is thrown while runningdoRun
- See Also:
-
isEventDispatchThread
public static boolean isEventDispatchThread()Returns true if the current thread is an AWT event dispatching thread.As of 1.3 this method is just a cover for
java.awt.EventQueue.isDispatchThread()
.- Returns:
- true if the current thread is an AWT event dispatching thread
-
getAccessibleIndexInParent
Get the index of this object in its accessible parent.Note: as of the Java 2 platform v1.3, it is recommended that developers call Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead of using this method.
- Parameters:
c
- the component- Returns:
- -1 of this object does not have an accessible parent. Otherwise, the index of the child in its accessible parent.
-
getAccessibleAt
Returns theAccessible
child contained at the local coordinatePoint
, if one exists. Otherwise returnsnull
.- Parameters:
c
- the componentp
- the local coordinate- Returns:
- the
Accessible
at the specified location, if it exists; otherwisenull
-
getAccessibleStateSet
Get the state of this object.Note: as of the Java 2 platform v1.3, it is recommended that developers call Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead of using this method.
- Parameters:
c
- the component- Returns:
- an instance of AccessibleStateSet containing the current state set of the object
- See Also:
-
getAccessibleChildrenCount
Returns the number of accessible children in the object. If all of the children of this object implement Accessible, than this method should return the number of children of this object.Note: as of the Java 2 platform v1.3, it is recommended that developers call Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead of using this method.
- Parameters:
c
- the component- Returns:
- the number of accessible children in the object.
-
getAccessibleChild
Return the nth Accessible child of the object.Note: as of the Java 2 platform v1.3, it is recommended that developers call Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead of using this method.
- Parameters:
c
- the componenti
- zero-based index of child- Returns:
- the nth Accessible child of the object
-
findFocusOwner
Deprecated.As of 1.4, replaced byKeyboardFocusManager.getFocusOwner()
.Return the childComponent
of the specifiedComponent
that is the focus owner, if any.- Parameters:
c
- the root of theComponent
hierarchy to search for the focus owner- Returns:
- the focus owner, or
null
if there is no focus owner, or if the focus owner is notcomp
, or a descendant ofcomp
- See Also:
-
getRootPane
-
getRoot
-
processKeyBindings
Process the key bindings for theComponent
associated withevent
. This method is only useful ifevent.getComponent()
does not descend fromJComponent
, or your are not invokingsuper.processKeyEvent
from within yourJComponent
subclass.JComponent
automatically processes bindings from within itsprocessKeyEvent
method, hence you rarely need to directly invoke this method.- Parameters:
event
- KeyEvent used to identify which bindings to process, as well as which Component has focus.- Returns:
- true if a binding has found and processed
- Since:
- 1.4
-
notifyAction
public static boolean notifyAction(Action action, KeyStroke ks, KeyEvent event, Object sender, int modifiers) InvokesactionPerformed
onaction
ifaction
is non-null
and accepts the sender object. The command for the ActionEvent is determined by:- If the action was registered via
registerKeyboardAction
, then the command string passed in (null
will be used ifnull
was passed in). - Action value with name Action.ACTION_COMMAND_KEY, unless
null
. - String value of the KeyEvent, unless
getKeyChar
returns KeyEvent.CHAR_UNDEFINED..
action
is non-null
and actionPerformed is invoked on it.- Parameters:
action
- an actionks
- a key strokeevent
- a key eventsender
- a sendermodifiers
- action modifiers- Returns:
true
ifaction
is non-null
and actionPerformed is invoked on it.- Since:
- 1.3
- See Also:
- If the action was registered via
-
replaceUIInputMap
Convenience method to change the UI InputMap forcomponent
touiInputMap
. IfuiInputMap
isnull
, this removes any previously installed UI InputMap.- Parameters:
component
- a componenttype
- a typeuiInputMap
- anInputMap
- Since:
- 1.3
-
replaceUIActionMap
Convenience method to change the UI ActionMap forcomponent
touiActionMap
. IfuiActionMap
isnull
, this removes any previously installed UI ActionMap.- Parameters:
component
- a componentuiActionMap
- anActionMap
- Since:
- 1.3
-
getUIInputMap
Returns the InputMap provided by the UI for conditioncondition
in componentcomponent
.This will return
null
if the UI has not installed an InputMap of the specified type.- Parameters:
component
- a componentcondition
- a condition- Returns:
- the
ActionMap
provided by the UI forcondition
in the component, ornull
if the UI has not installed an InputMap of the specified type. - Since:
- 1.3
-
getUIActionMap
Returns the ActionMap provided by the UI in componentcomponent
.This will return
null
if the UI has not installed an ActionMap.- Parameters:
component
- a component- Returns:
- the
ActionMap
provided by the UI in the component, ornull
if the UI has not installed an ActionMap. - Since:
- 1.3
-
calculateInnerArea
Stores the position and size of the inner painting area of the specified component inr
and returnsr
. The position and size specify the bounds of the component, adjusted so as not to include the border area (the insets). This method is useful for classes that implement painting code.- Parameters:
c
- the JComponent in question; ifnull
, this method returnsnull
r
- the Rectangle instance to be modified; may benull
- Returns:
null
if the Component isnull
; otherwise, returns the passed-in rectangle (if non-null
) or a new rectangle specifying position and size information- Since:
- 1.4
-
getUnwrappedParent
Returns the first ancestor of thecomponent
which is not an instance ofJLayer
.- Parameters:
component
-Component
to get the first ancestor of, which is not aJLayer
instance.- Returns:
- the first ancestor of the
component
which is not an instance ofJLayer
. If such an ancestor can not be found,null
is returned. - Throws:
NullPointerException
- ifcomponent
isnull
- Since:
- 1.7
- See Also:
-
getUnwrappedView
Returns the firstJViewport
's descendant which is not an instance ofJLayer
. If such a descendant can not be found,null
is returned. If theviewport
's view component is not aJLayer
, this method is equivalent toJViewport.getView()
otherwiseJLayer.getView()
will be recursively called on all descendingJLayer
s.- Parameters:
viewport
-JViewport
to get the first descendant of, which in not aJLayer
instance.- Returns:
- the first
JViewport
's descendant which is not an instance ofJLayer
. If such a descendant can not be found,null
is returned. - Throws:
NullPointerException
- ifviewport
isnull
- Since:
- 1.7
- See Also:
-
KeyboardFocusManager.getFocusOwner()
.