SwingConstants
public class SwingUtilities extends Object implements SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Modifier and Type | Method | Description |
---|---|---|
static Rectangle |
calculateInnerArea |
Stores the position and size of the inner painting area of the specified component in r and returns r . |
static Rectangle[] |
computeDifference |
Convenience returning an array of rect representing the regions within rectA that do not overlap with rectB . |
static Rectangle |
computeIntersection |
Convenience to calculate the intersection of two rectangles without allocating a new rectangle. |
static int |
computeStringWidth |
Compute the width of the string using a font with the specified "metrics" (sizes). |
static Rectangle |
computeUnion |
Convenience method that calculates the union of two rectangles without allocating a new rectangle. |
static MouseEvent |
convertMouseEvent |
Returns a MouseEvent similar to sourceEvent except that its x and y members have been converted to destination 's coordinate system. |
static Point |
convertPoint |
Convert the point (x,y) in source coordinate system to destination coordinate system. |
static Point |
convertPoint |
Convert a aPoint in source coordinate system to destination coordinate system. |
static void |
convertPointFromScreen |
Convert a point from a screen coordinates to a component's coordinate system |
static void |
convertPointToScreen |
Convert a point from a component's coordinate system to screen coordinates. |
static Rectangle |
convertRectangle |
Convert the rectangle aRectangle in source coordinate system to destination coordinate system. |
static Component |
findFocusOwner |
Deprecated. |
static Accessible |
getAccessibleAt |
Returns the Accessible child contained at the local coordinate Point , if one exists. |
static Accessible |
getAccessibleChild |
Return the nth Accessible child of the object. |
static int |
getAccessibleChildrenCount |
Returns the number of accessible children in the object. |
static int |
getAccessibleIndexInParent |
Get the index of this object in its accessible parent. |
static AccessibleStateSet |
getAccessibleStateSet |
Get the state of this object. |
static Container |
getAncestorNamed |
Convenience method for searching above comp in the component hierarchy and returns the first object of name it finds. |
static Container |
getAncestorOfClass |
Convenience method for searching above comp in the component hierarchy and returns the first object of class c it finds. |
static Component |
getDeepestComponentAt |
Returns the deepest visible descendent Component of parent that contains the location x , y . |
static Rectangle |
getLocalBounds |
Return the rectangle (0,0,bounds.width,bounds.height) for the component aComponent
|
static Component |
getRoot |
Returns the root component for the current component tree. |
static JRootPane |
getRootPane |
If c is a JRootPane descendant return its JRootPane ancestor. |
static ActionMap |
getUIActionMap |
Returns the ActionMap provided by the UI in component component . |
static InputMap |
getUIInputMap |
Returns the InputMap provided by the UI for condition condition in component component . |
static Container |
getUnwrappedParent |
Returns the first ancestor of the component which is not an instance of JLayer . |
static Component |
getUnwrappedView |
Returns the first JViewport 's descendant which is not an instance of JLayer . |
static Window |
getWindowAncestor |
Returns the first Window ancestor of c , or null if c is not contained inside a Window . |
static void |
invokeAndWait |
Causes doRun.run() to be executed synchronously on the AWT event dispatching thread. |
static void |
invokeLater |
Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. |
static boolean |
isDescendingFrom |
Return true if a component a descends from a component b
|
static boolean |
isEventDispatchThread() |
Returns true if the current thread is an AWT event dispatching thread. |
static boolean |
isLeftMouseButton |
Returns true if the mouse event specifies the left mouse button. |
static boolean |
isMiddleMouseButton |
Returns true if the mouse event specifies the middle mouse button. |
static final boolean |
isRectangleContainingRectangle |
Return true if a contains b
|
static boolean |
isRightMouseButton |
Returns true if the mouse event specifies the right mouse button. |
static String |
layoutCompoundLabel |
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 |
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 |
Invokes actionPerformed on action if action is non-null and accepts the sender object. |
static void |
paintComponent |
Paints a component to the specified Graphics . |
static void |
paintComponent |
Paints a component to the specified Graphics . |
static boolean |
processKeyBindings |
Process the key bindings for the Component associated with event . |
static void |
replaceUIActionMap |
Convenience method to change the UI ActionMap for component to uiActionMap . |
static void |
replaceUIInputMap |
Convenience method to change the UI InputMap for component to uiInputMap . |
static void |
updateComponentTreeUI |
A simple minded look and feel change: ask each node in the tree to updateUI() -- that is, to initialize its UI property with the current look and feel. |
static Window |
windowForComponent |
Returns the first Window ancestor of c , or null if c is not contained inside a Window . |
public static final boolean isRectangleContainingRectangle(Rectangle a, Rectangle b)
true
if a
contains b
a
- the first rectangleb
- the second rectangletrue
if a
contains b
public static Rectangle getLocalBounds(Component aComponent)
aComponent
aComponent
- a componentaComponent
public static Window getWindowAncestor(Component c)
Window
ancestor of c
, or null
if c
is not contained inside a Window
.c
- Component
to get Window
ancestor of.Window
ancestor of c
, or null
if c
is not contained inside a Window
.public static Point convertPoint(Component source, Point aPoint, Component destination)
aPoint
in source
coordinate system to destination
coordinate system. If source
is null
, aPoint
is assumed to be in destination
's root component coordinate system. If destination
is null
, aPoint
will be converted to source
's root component coordinate system. If both source
and destination
are null
, return aPoint
without any conversion.source
- the source componentaPoint
- the pointdestination
- the destination componentpublic static Point convertPoint(Component source, int x, int y, Component destination)
(x,y)
in source
coordinate system to destination
coordinate system. If source
is null
, (x,y)
is assumed to be in destination
's root component coordinate system. If destination
is null
, (x,y)
will be converted to source
's root component coordinate system. If both source
and destination
are null
, return (x,y)
without any conversion.source
- the source componentx
- the x-coordinate of the pointy
- the y-coordinate of the pointdestination
- the destination componentpublic static Rectangle convertRectangle(Component source, Rectangle aRectangle, Component destination)
aRectangle
in source
coordinate system to destination
coordinate system. If source
is null
, aRectangle
is assumed to be in destination
's root component coordinate system. If destination
is null
, aRectangle
will be converted to source
's root component coordinate system. If both source
and destination
are null
, return aRectangle
without any conversion.source
- the source componentaRectangle
- a rectangledestination
- the destination componentpublic static Container getAncestorOfClass(Class<?> c, Component comp)
comp
in the component hierarchy and returns the first object of class c
it finds. Can return null
, if a class c
cannot be found.c
- the class of a componentcomp
- the componentcomp
, or null
if c
cannot be found.public static Container getAncestorNamed(String name, Component comp)
comp
in the component hierarchy and returns the first object of name
it finds. Can return null
, if name
cannot be found.name
- the name of a componentcomp
- the componentcomp
, or null
if name
cannot be found.public static Component getDeepestComponentAt(Component parent, int x, int y)
parent
that contains the location x
, y
. If parent
does not contain the specified location, then null
is returned. If parent
is not a container, or none of parent
's visible descendents contain the specified location, parent
is returned.parent
- the root component to begin the searchx
- the x target locationy
- the y target locationpublic static MouseEvent convertMouseEvent(Component source, MouseEvent sourceEvent, Component destination)
sourceEvent
except that its x and y members have been converted to destination
's coordinate system. If source
is null
, sourceEvent
x and y members are assumed to be into destination
's root component coordinate system. If destination
is null
, the returned MouseEvent will be in source
's coordinate system. sourceEvent
will not be changed. A new event is returned. the source
field of the returned event will be set to destination
if destination is non-null
use the translateMouseEvent() method to translate a mouse event from one component to another without changing the source.source
- the source componentsourceEvent
- the source mouse eventdestination
- the destination componentpublic static void convertPointToScreen(Point p, Component c)
p
- a Point object (converted to the new coordinate system)c
- a Component objectpublic static void convertPointFromScreen(Point p, Component c)
p
- a Point object (converted to the new coordinate system)c
- a Component objectpublic static Window windowForComponent(Component c)
Window
ancestor of c
, or null
if c
is not contained inside a Window
. Note: This method provides the same functionality as getWindowAncestor
.
c
- Component
to get Window
ancestor of.Window
ancestor of c
, or null
if c
is not contained inside a Window
.public static boolean isDescendingFrom(Component a, Component b)
true
if a component a
descends from a component b
a
- the first componentb
- the second componenttrue
if a component a
descends from a component b
public static Rectangle computeIntersection(int x, int y, int width, int height, Rectangle dest)
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 rectangledest
, modified to specify the intersectionpublic static Rectangle computeUnion(int x, int y, int width, int height, Rectangle dest)
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 rectangledest
Rectangle
public static Rectangle[] computeDifference(Rectangle rectA, Rectangle rectB)
rectA
that do not overlap with rectB
. If the two Rects do not overlap, returns an empty arrayrectA
- the first rectanglerectB
- the second rectanglerectA
that do not overlap with rectB
.public static boolean isLeftMouseButton(MouseEvent anEvent)
anEvent
- a MouseEvent objectpublic static boolean isMiddleMouseButton(MouseEvent anEvent)
anEvent
- a MouseEvent objectpublic static boolean isRightMouseButton(MouseEvent anEvent)
anEvent
- a MouseEvent objectpublic static int computeStringWidth(FontMetrics fm, String str)
fm
- a FontMetrics object to compute withstr
- the String to computepublic 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)
c
- the componentfm
- the instance of FontMetrics
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 iconpublic 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)
fm
- the instance of FontMetrics
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 iconpublic static void paintComponent(Graphics g, Component c, Container p, int x, int y, int w, int h)
Graphics
. This method is primarily useful to render Component
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 of JLabel
'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, as JTable
does, use CellRendererPane
directly. Otherwise, as described below, you could end up with a CellRendererPane
per Component
.
If c
's parent is not a CellRendererPane
, a new CellRendererPane
is created, c
is added to it, and the CellRendererPane
is added to p
. If c
's parent is a CellRendererPane
and the CellRendererPane
s parent is not p
, it is added to p
.
The component should either descend from JComponent
or be another kind of lightweight component. A lightweight component is one whose "lightweight" property (returned by the Component
isLightweight
method) is true. If the Component is not lightweight, bad things map happen: crashes, exceptions, painting problems...
g
- the Graphics
object to draw onc
- the Component
to drawp
- the intermediate Container
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 pixelspublic static void paintComponent(Graphics g, Component c, Container p, Rectangle r)
Graphics
. This is a cover method for paintComponent(Graphics,Component,Container,int,int,int,int)
. Refer to it for more information.g
- the Graphics
object to draw onc
- the Component
to drawp
- the intermediate Container
r
- the Rectangle
to draw inpublic static void updateComponentTreeUI(Component c)
updateUI()
-- that is, to initialize its UI property with the current look and feel.c
- the componentpublic static void invokeLater(Runnable doRun)
invokeLater
call queues the Runnable
object doHelloWorld
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.
doRun
- the instance of Runnable
public static void invokeAndWait(Runnable doRun) throws InterruptedException, InvocationTargetException
doRun.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 uses invokeAndWait
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 the
Runnable.run
method throws an uncaught exception (on the event dispatching thread) it's caught and rethrown, as an InvocationTargetException
, 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()
.
doRun
- the instance of Runnable
InterruptedException
- if we're interrupted while waiting for the event dispatching thread to finish executing doRun.run()
InvocationTargetException
- if an exception is thrown while running doRun
public static boolean isEventDispatchThread()
As of 1.3 this method is just a cover for java.awt.EventQueue.isDispatchThread()
.
public static int getAccessibleIndexInParent(Component c)
Note: as of the Java 2 platform v1.3, it is recommended that developers call Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead of using this method.
c
- the componentpublic static Accessible getAccessibleAt(Component c, Point p)
Accessible
child contained at the local coordinate Point
, if one exists. Otherwise returns null
.c
- the componentp
- the local coordinateAccessible
at the specified location, if it exists; otherwise null
public static AccessibleStateSet getAccessibleStateSet(Component c)
Note: as of the Java 2 platform v1.3, it is recommended that developers call Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead of using this method.
c
- the componentpublic static int getAccessibleChildrenCount(Component c)
Note: as of the Java 2 platform v1.3, it is recommended that developers call Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead of using this method.
c
- the componentpublic static Accessible getAccessibleChild(Component c, int i)
Note: as of the Java 2 platform v1.3, it is recommended that developers call Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead of using this method.
c
- the componenti
- zero-based index of child@Deprecated public static Component findFocusOwner(Component c)
KeyboardFocusManager.getFocusOwner()
.Component
of the specified Component
that is the focus owner, if any.c
- the root of the Component
hierarchy to search for the focus ownernull
if there is no focus owner, or if the focus owner is not comp
, or a descendant of comp
public static JRootPane getRootPane(Component c)
c
- the componentnull
.public static Component getRoot(Component c)
c
- the componentpublic static boolean processKeyBindings(KeyEvent event)
Component
associated with event
. This method is only useful if event.getComponent()
does not descend from JComponent
, or your are not invoking super.processKeyEvent
from within your JComponent
subclass. JComponent
automatically processes bindings from within its processKeyEvent
method, hence you rarely need to directly invoke this method.event
- KeyEvent used to identify which bindings to process, as well as which Component has focus.public static boolean notifyAction(Action action, KeyStroke ks, KeyEvent event, Object sender, int modifiers)
actionPerformed
on action
if action
is non-null
and accepts the sender object. The command for the ActionEvent is determined by: registerKeyboardAction
, then the command string passed in (null
will be used if null
was passed in). null
. getKeyChar
returns KeyEvent.CHAR_UNDEFINED.. action
is non-null
and actionPerformed is invoked on it.action
- an actionks
- a key strokeevent
- a key eventsender
- a sendermodifiers
- action modifierstrue
if action
is non-null
and actionPerformed is invoked on it.public static void replaceUIInputMap(JComponent component, int type, InputMap uiInputMap)
component
to uiInputMap
. If uiInputMap
is null
, this removes any previously installed UI InputMap.component
- a componenttype
- a typeuiInputMap
- an InputMap
public static void replaceUIActionMap(JComponent component, ActionMap uiActionMap)
component
to uiActionMap
. If uiActionMap
is null
, this removes any previously installed UI ActionMap.component
- a componentuiActionMap
- an ActionMap
public static InputMap getUIInputMap(JComponent component, int condition)
condition
in component component
. This will return null
if the UI has not installed an InputMap of the specified type.
component
- a componentcondition
- a conditionActionMap
provided by the UI for condition
in the component, or null
if the UI has not installed an InputMap of the specified type.public static ActionMap getUIActionMap(JComponent component)
component
. This will return null
if the UI has not installed an ActionMap.
component
- a componentActionMap
provided by the UI in the component, or null
if the UI has not installed an ActionMap.public static Rectangle calculateInnerArea(JComponent c, Rectangle r)
r
and returns r
. 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.c
- the JComponent in question; if null
, this method returns null
r
- the Rectangle instance to be modified; may be null
null
if the Component is null
; otherwise, returns the passed-in rectangle (if non-null
) or a new rectangle specifying position and size informationpublic static Container getUnwrappedParent(Component component)
component
which is not an instance of JLayer
.component
- Component
to get the first ancestor of, which is not a JLayer
instance.component
which is not an instance of JLayer
. If such an ancestor can not be found, null
is returned.NullPointerException
- if component
is null
public static Component getUnwrappedView(JViewport viewport)
JViewport
's descendant which is not an instance of JLayer
. If such a descendant can not be found, null
is returned. If the viewport
's view component is not a JLayer
, this method is equivalent to JViewport.getView()
otherwise JLayer.getView()
will be recursively called on all descending JLayer
s.viewport
- JViewport
to get the first descendant of, which in not a JLayer
instance.JViewport
's descendant which is not an instance of JLayer
. If such a descendant can not be found, null
is returned.NullPointerException
- if viewport
is null
© 1993, 2023, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/SwingUtilities.html
KeyboardFocusManager.getFocusOwner()
.