Class GraphicsUtils
Graphics context
Every drawing method in this class accepts a Graphics2D context
directly. The legacy Graphics parameter type has been
removed throughout; no internal casts are performed.
Note for callers that override Component.paint(java.awt.Graphics):
Java AWT declares paint(Graphics g) with a fixed signature. Inside
that override, cast once at the entry point and pass the result to these
utilities:
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
GraphicsUtils.drawHighlightedRectangle(g2, rect);
}
Stroke caching
BasicStroke objects are expensive to construct and are immutable.
getStroke(float, LineStyle) caches every stroke it creates in
strokes so that repeated calls with the same parameters return the
same object without allocation.
Highlighted drawing
"Highlighted" shapes (rectangles, ovals, polylines, etc.) are drawn twice
with complementary dashed strokes — dash1/dash2 or
dash1_2/dash2_2 — in two alternating colors. The result
is a marching-ants selection indicator. Default colors are
highlightColor1 (red) and highlightColor2 (yellow).
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final BasicStroke1-pixel dashed stroke, phase 0 — first pass of a marching-ants pair.static final BasicStroke2-pixel dashed stroke, phase 0 — first pass of a medium-weight marching-ants pair.static final BasicStroke4-pixel dashed stroke, phase 0 — first pass of a thick marching-ants pair.static final BasicStroke1-pixel dashed stroke, phase 8 — second pass of a marching-ants pair.static final BasicStroke2-pixel dashed stroke, phase 8 — second pass of a medium-weight marching-ants pair.static final BasicStroke4-pixel dashed stroke, phase 8 — second pass of a thick marching-ants pair.static final ColorPrimary color used for highlighted (marching-ants) drawing.static final ColorSecondary color used for highlighted (marching-ants) drawing.static final BasicStroke1-pixel dashed stroke, phase 8.static final BasicStroke1-pixel dashed stroke, phase 0.5. -
Method Summary
Modifier and TypeMethodDescriptionstatic ColorcolorFromHex(String hex) Parse a hex color string in common internet format.static StringcolorToHex(Color color) Convert aColorto an 8-digit hex string in#rrggbbaaformat.static BasicStrokecopyWithNewWidth(BasicStroke original, float newWidth) Copy aBasicStroke, replacing its width withnewWidthwhile preserving all other attributes (cap, join, miter limit, dash array, and dash phase).static voiddrawEtchedText(Graphics2D g2, String text, int x, int y) Draw etched text.static voiddrawHighlightedArc(Graphics2D g2, int x, int y, int width, int height, int startAngle, int arcAngle, Color color1, Color color2) Draw a highlighted (marching-ants) arc.static voiddrawHighlightedLine(Graphics2D g2, int x1, int y1, int x2, int y2, Color color1, Color color2) Draw a highlighted (marching-ants) line segment.static voidDraw a highlighted oval using the default colors (highlightColor1andhighlightColor2).static voiddrawHighlightedOval(Graphics2D g2, Rectangle r, Color color1, Color color2) Draw a highlighted (marching-ants) oval outline.static voiddrawHighlightedPolyline(Graphics2D g2, int[] x, int[] y, int n) Draw a highlighted polyline using the default colors (highlightColor1andhighlightColor2).static voiddrawHighlightedPolyline(Graphics2D g2, int[] x, int[] y, int n, Color color1, Color color2) Draw a highlighted (marching-ants) open polyline.static voidDraw a highlighted rectangle using the default colors (highlightColor1andhighlightColor2).static voiddrawHighlightedRectangle(Graphics2D g2, Rectangle r, Color color1, Color color2) Draw a highlighted (marching-ants) rectangle outline.static voiddrawHighlightedShape(Graphics2D g2, Shape shape) Draw a highlighted shape using the default colors (highlightColor1andhighlightColor2).static voiddrawHighlightedShape(Graphics2D g2, Shape shape, Color color1, Color color2) Draw a highlighted (marching-ants) arbitraryShapeoutline.static voiddrawRotatedText(Graphics2D g2, String s, Font font, int x, int y, double angleDegrees) Draw a string at the given position, rotated byangleDegreesaround its baseline anchor.static voiddrawRotatedText(Graphics2D g2, String s, Font font, int xo, int yo, int delX, int delY, double angleDegrees) Draw a string rotated around an anchor point with an additional unrotated offset applied before rotation.static voiddrawSimple3DRect(Graphics2D g2, int x, int y, int width, int height, boolean raised) Draws a simple one-pixel 3D border around a rectangle using brighter and darker variants of the graphics context's current color.static voiddrawStyleLine(Graphics2D g2, Color lineColor, float lineWidth, LineStyle lineStyle, int x1, int y1, int x2, int y2) Draw a line with explicit color, width, and dash style.static voiddrawThickHighlightedLine(Graphics2D g2, int x1, int y1, int x2, int y2, Color color1, Color color2) Draw a thick highlighted (marching-ants) line segment.static BufferedImageRendercto a newBufferedImageand return it.static BufferedImageAllocate an opaqueBufferedImagelarge enough to hold an off-screen rendering ofc.static BufferedImageAllocate a translucentBufferedImagelarge enough to hold an off-screen rendering ofc.static ContainergetParentContainer(Component component) Walk up the component hierarchy and return the first ancestor that is aJInternalFrame,JDialog, orWindow.static BasicStrokeReturn a cachedBasicStrokefor the given line width and style.static RectangleCompute the intersection of a current clip shape with a rectangle.static voidpaintComponentOnImage(Component c, BufferedImage image) Paintconto an existingBufferedImage.static booleanpointOnLine(int px, int py, int startx, int starty, int endx, int endy) Test whether a pixel point lies on a pixel line segment within the tolerance defined bySELECTRES.static booleanpointOnLine(Point p, Point start, Point end) Test whether a pixel point lies on a pixel line segment within the tolerance defined bySELECTRES.static RectanglerectangleFromPoints(Point p1, Point p2) Build aRectanglefrom two arbitrary corner points.static Point[]rectangleToPoints(Rectangle rect) static voidsetSizeMini(JComponent component) Apply the "mini" size variant to a Swing component.static voidsetSizeSmall(JComponent component) Apply the "small" size variant to a Swing component.static voidsetSquareButton(JButton button) Apply the square button style to aJButton.static voidsetTexturedButton(JButton button) Apply the textured button style to aJButton.
-
Field Details
-
highlightColor1
Primary color used for highlighted (marching-ants) drawing. Defaults toColor.red. -
highlightColor2
Secondary color used for highlighted (marching-ants) drawing. Defaults toColor.yellow. -
dash1
1-pixel dashed stroke, phase 0 — first pass of a marching-ants pair. Used withdash2to draw highlighted outlines. -
dash2
1-pixel dashed stroke, phase 8 — second pass of a marching-ants pair. Used withdash1to draw highlighted outlines. -
dash1_2
2-pixel dashed stroke, phase 0 — first pass of a medium-weight marching-ants pair. Used withdash2_2. -
dash2_2
2-pixel dashed stroke, phase 8 — second pass of a medium-weight marching-ants pair. Used withdash1_2. -
dash1_2t
4-pixel dashed stroke, phase 0 — first pass of a thick marching-ants pair. Used withdash2_2t. -
dash2_2t
4-pixel dashed stroke, phase 8 — second pass of a thick marching-ants pair. Used withdash1_2t. -
simpleDash
1-pixel dashed stroke, phase 8. A convenient general-purpose dashed stroke for non-highlighted use. -
simpleDash2
1-pixel dashed stroke, phase 0.5. A slight phase offset fromsimpleDashfor situations where two complementary dashed lines are needed without the full marching-ants machinery.
-
-
Method Details
-
setSizeSmall
Apply the "small" size variant to a Swing component.This is a macOS-specific client property that instructs the native look-and-feel to render the component at a reduced size. It has no effect on other platforms.
- Parameters:
component- the component to resize; must not benull
-
setSizeMini
Apply the "mini" size variant to a Swing component.This is a macOS-specific client property that instructs the native look-and-feel to render the component at its smallest available size. It has no effect on other platforms.
- Parameters:
component- the component to resize; must not benull
-
setSquareButton
Apply the square button style to aJButton.On macOS this suppresses the default rounded-capsule style in favour of a square-cornered button that is more compact in tight layouts. Has no effect on other platforms.
- Parameters:
button- the button to restyle; must not benull
-
setTexturedButton
Apply the textured button style to aJButton.On macOS this gives the button a brushed-metal texture suitable for toolbar-adjacent controls. Has no effect on other platforms.
- Parameters:
button- the button to restyle; must not benull
-
minClip
Compute the intersection of a current clip shape with a rectangle.Returns the intersection bounding rectangle, or
nullif either argument isnull, degenerate (zero area), or if the intersection is empty.- Parameters:
currentClip- the current clip shape (e.g. fromGraphics.getClip())rect- the rectangle to intersect with the clip- Returns:
- the intersection as a
Rectangle, ornull
-
getStroke
Return a cachedBasicStrokefor the given line width and style.The first call for any (width, style) combination creates and caches the stroke; subsequent calls return the cached instance. A width of zero is treated identically to a width of one.
Supported styles and their dash patterns:
LineStyle.SOLID— no dash (round cap/join)LineStyle.DASH— 10 on, 10 offLineStyle.DOT_DASH— 4-4-10-4LineStyle.DOT— 4 on, 4 offLineStyle.DOUBLE_DASH— 10-4-10-10LineStyle.LONG_DASH— 15 on, 15 offLineStyle.LONG_DOT_DASH— 6-4-15-4
- Parameters:
lineWidth- the desired stroke width in pixelslineStyle- the dash pattern style; must not benull- Returns:
- a
BasicStrokematching the requested parameters
-
copyWithNewWidth
Copy aBasicStroke, replacing its width withnewWidthwhile preserving all other attributes (cap, join, miter limit, dash array, and dash phase).- Parameters:
original- the stroke to copy; must not benullnewWidth- the replacement width in pixels- Returns:
- a new
BasicStrokeidentical tooriginalexcept for the width
-
rectangleToPoints
Return the four corners of aRectangleas an array ofPointobjects.Corners are returned in order: top-left, top-right, bottom-right, bottom-left. Useful for computing item selection handles.
- Parameters:
rect- the rectangle; must not benull- Returns:
- array of four corner points
-
rectangleFromPoints
Build aRectanglefrom two arbitrary corner points.The returned rectangle always has non-negative width and height, regardless of the relative positions of the two points.
- Parameters:
p1- one corner; ifnullandp2is non-null, returns a zero-size rectangle atp2p2- the opposite corner; ifnullandp1is non-null, returns a zero-size rectangle atp1- Returns:
- the bounding rectangle, or
nullif both points arenull
-
getComponentImageBuffer
Allocate an opaqueBufferedImagelarge enough to hold an off-screen rendering ofc.The image is not painted; call
paintComponentOnImage(Component, BufferedImage)separately. Returnsnullifcisnullor has zero size.- Parameters:
c- the component whose size determines the image dimensions- Returns:
- a new
TYPE_INT_RGBimage, ornull
-
getComponentTranslucentImageBuffer
Allocate a translucentBufferedImagelarge enough to hold an off-screen rendering ofc.Use this instead of
getComponentImageBuffer(java.awt.Component)when the component may have transparent or semi-transparent regions. Returnsnullifcisnullor has zero size.- Parameters:
c- the component whose size determines the image dimensions- Returns:
- a new translucent image, or
null
-
paintComponentOnImage
Paintconto an existingBufferedImage.A
Graphics2Dcontext is obtained from the image, the component is painted, and the context is disposed. The image must be at least as large as the component.- Parameters:
c- the component to paint; no-op ifnullimage- the target image; no-op ifnull
-
getComponentImage
Rendercto a newBufferedImageand return it.Combines
getComponentImageBuffer(java.awt.Component)andpaintComponentOnImage(java.awt.Component, java.awt.image.BufferedImage)in a single call.- Parameters:
c- the component to render; may returnnullifcisnullor has zero size- Returns:
- an image containing the rendered component, or
null
-
drawSimple3DRect
public static void drawSimple3DRect(Graphics2D g2, int x, int y, int width, int height, boolean raised) Draws a simple one-pixel 3D border around a rectangle using brighter and darker variants of the graphics context's current color.- Parameters:
g2- the graphics contextx- the left edgey- the top edgewidth- the rectangle widthheight- the rectangle heightraised-truefor a raised appearance;falsefor a recessed appearance
-
drawEtchedText
Draw etched text.The string is drawn twice: first in white at
(x+1, y+1)to create a shadow, then in black at(x, y). This makes the text readable against any background color.- Parameters:
g2- the graphics contexttext- the string to draw; must not benullx- the x pixel coordinate of the text baseline anchory- the y pixel coordinate of the text baseline
-
drawRotatedText
public static void drawRotatedText(Graphics2D g2, String s, Font font, int x, int y, double angleDegrees) Draw a string at the given position, rotated byangleDegreesaround its baseline anchor.If the angle is less than 0.5° (effectively zero) the text is drawn normally without any rotation transform.
- Parameters:
g2- the graphics contexts- the string to draw; must not benullfont- the font to usex- the x pixel coordinate of the baseline anchory- the y pixel coordinate of the baseline anchorangleDegrees- the counter-clockwise rotation angle in degrees
-
drawRotatedText
public static void drawRotatedText(Graphics2D g2, String s, Font font, int xo, int yo, int delX, int delY, double angleDegrees) Draw a string rotated around an anchor point with an additional unrotated offset applied before rotation.The offset
(delX, delY)is first rotated byangleDegreesand then added to the anchor(xo, yo)to determine where the string baseline is drawn.If the angle is less than 0.5° (effectively zero) the text is drawn normally at
(xo + delX, yo + delY)without any rotation transform, which avoids floating-point error in the identity case.- Parameters:
g2- the graphics contexts- the string to draw; must not benullfont- the font to usexo- the x pixel coordinate of the rotation anchoryo- the y pixel coordinate of the rotation anchordelX- horizontal offset from the anchor, measured before rotation is applieddelY- vertical offset from the anchor, measured before rotation is appliedangleDegrees- the counter-clockwise rotation angle in degrees
-
drawStyleLine
public static void drawStyleLine(Graphics2D g2, Color lineColor, float lineWidth, LineStyle lineStyle, int x1, int y1, int x2, int y2) Draw a line with explicit color, width, and dash style.The graphics context's stroke is restored to its previous value after drawing.
- Parameters:
g2- the graphics contextlineColor- the line color; must not benulllineWidth- the line width in pixelslineStyle- the dash stylex1- x pixel coordinate of the start pointy1- y pixel coordinate of the start pointx2- x pixel coordinate of the end pointy2- y pixel coordinate of the end point
-
drawHighlightedRectangle
Draw a highlighted rectangle using the default colors (highlightColor1andhighlightColor2).- Parameters:
g2- the graphics contextr- the rectangle to highlight; no-op ifnull
-
drawHighlightedRectangle
Draw a highlighted (marching-ants) rectangle outline.The rectangle is drawn twice: once with
dash1incolor1and once withdash2incolor2. The complementary dash phases produce the marching-ants effect.- Parameters:
g2- the graphics context; no-op ifnullr- the rectangle to highlight; no-op ifnullcolor1- primary dash colorcolor2- secondary dash color
-
drawHighlightedLine
public static void drawHighlightedLine(Graphics2D g2, int x1, int y1, int x2, int y2, Color color1, Color color2) Draw a highlighted (marching-ants) line segment.The line is drawn twice with
dash1_2anddash2_2(2-pixel width) in alternating colors.- Parameters:
g2- the graphics contextx1- x pixel coordinate of the start pointy1- y pixel coordinate of the start pointx2- x pixel coordinate of the end pointy2- y pixel coordinate of the end pointcolor1- primary dash colorcolor2- secondary dash color
-
drawThickHighlightedLine
public static void drawThickHighlightedLine(Graphics2D g2, int x1, int y1, int x2, int y2, Color color1, Color color2) Draw a thick highlighted (marching-ants) line segment.Identical to
drawHighlightedLine(java.awt.Graphics2D, int, int, int, int, java.awt.Color, java.awt.Color)but usesdash1_2tanddash2_2t(4-pixel width) for a more prominent indicator.- Parameters:
g2- the graphics contextx1- x pixel coordinate of the start pointy1- y pixel coordinate of the start pointx2- x pixel coordinate of the end pointy2- y pixel coordinate of the end pointcolor1- primary dash colorcolor2- secondary dash color
-
drawHighlightedArc
public static void drawHighlightedArc(Graphics2D g2, int x, int y, int width, int height, int startAngle, int arcAngle, Color color1, Color color2) Draw a highlighted (marching-ants) arc.The arc is drawn twice with
dash1anddash2(1-pixel width) in alternating colors.- Parameters:
g2- the graphics contextx- x pixel coordinate of the bounding rectangle's top-left cornery- y pixel coordinate of the bounding rectangle's top-left cornerwidth- width of the bounding rectangle in pixelsheight- height of the bounding rectangle in pixelsstartAngle- start angle of the arc in degrees (0 = 3 o'clock, measured counter-clockwise)arcAngle- angular extent of the arc in degreescolor1- primary dash colorcolor2- secondary dash color
-
drawHighlightedOval
Draw a highlighted oval using the default colors (highlightColor1andhighlightColor2).- Parameters:
g2- the graphics contextr- the bounding rectangle of the oval; no-op ifnull
-
drawHighlightedOval
Draw a highlighted (marching-ants) oval outline.The oval is drawn twice with
dash1anddash2(1-pixel width) in alternating colors.- Parameters:
g2- the graphics context; no-op ifnullr- the bounding rectangle of the oval; no-op ifnullcolor1- primary dash colorcolor2- secondary dash color
-
drawHighlightedPolyline
Draw a highlighted polyline using the default colors (highlightColor1andhighlightColor2).- Parameters:
g2- the graphics contextx- x coordinate arrayy- y coordinate arrayn- number of points to draw
-
drawHighlightedPolyline
public static void drawHighlightedPolyline(Graphics2D g2, int[] x, int[] y, int n, Color color1, Color color2) Draw a highlighted (marching-ants) open polyline.The polyline is drawn twice with
dash1anddash2(1-pixel width) in alternating colors.- Parameters:
g2- the graphics contextx- x coordinate arrayy- y coordinate arrayn- number of points to drawcolor1- primary dash colorcolor2- secondary dash color
-
drawHighlightedShape
Draw a highlighted shape using the default colors (highlightColor1andhighlightColor2).- Parameters:
g2- the graphics contextshape- the shape to highlight; no-op ifnull
-
drawHighlightedShape
Draw a highlighted (marching-ants) arbitraryShapeoutline.The shape is drawn twice with
dash1anddash2(1-pixel width) in alternating colors.- Parameters:
g2- the graphics context; no-op ifnullshape- the shape to highlight; no-op ifnullcolor1- primary dash colorcolor2- secondary dash color
-
pointOnLine
public static boolean pointOnLine(int px, int py, int startx, int starty, int endx, int endy) Test whether a pixel point lies on a pixel line segment within the tolerance defined bySELECTRES.The test is performed in pixel space using a parametric projection. A point is considered "on" the line if:
- The projection of the point onto the infinite line through the
segment falls within the segment (
t ∈ [0, 1]), and - The perpendicular distance from the point to the line is less than
SELECTRESpixels.
If the segment is nearly degenerate (both
|Δx|and|Δy|are less than 2 pixels) the method returnsfalse.- Parameters:
px- x coordinate of the point to testpy- y coordinate of the point to teststartx- x coordinate of the segment startstarty- y coordinate of the segment startendx- x coordinate of the segment endendy- y coordinate of the segment end- Returns:
trueif the point is within tolerance of the segment
- The projection of the point onto the infinite line through the
segment falls within the segment (
-
pointOnLine
Test whether a pixel point lies on a pixel line segment within the tolerance defined bySELECTRES.- Parameters:
p- the point to test; no-op returnsfalseifnullstart- the start of the segment; no-op returnsfalseifnullend- the end of the segment; no-op returnsfalseifnull- Returns:
trueif the point is within tolerance of the segment- See Also:
-
colorToHex
Convert aColorto an 8-digit hex string in#rrggbbaaformat.All four channels (red, green, blue, alpha) are included. Returns
"#000000ff"(opaque black) ifcolorisnull.- Parameters:
color- the color to convert; may benull- Returns:
- hex string in the form
#rrggbbaa
-
colorFromHex
Parse a hex color string in common internet format.The string may be in any of these forms:
rrggbbaa— 8 hex digits, fully specifiedrrggbb— 6 hex digits; alpha defaults toff(fully opaque)#rrggbbaaor#rrggbb— leading#is optional
Strings shorter than 6 hex digits are zero-padded on the right. Returns
Color.blackifhexisnullor cannot be parsed.- Parameters:
hex- the hex color string; may benull- Returns:
- the corresponding
Color, orColor.blackon error
-
getParentContainer
Walk up the component hierarchy and return the first ancestor that is aJInternalFrame,JDialog, orWindow.Returns
nullif no such ancestor exists (e.g. the component has not been added to a window yet) or ifcomponentisnull.- Parameters:
component- the component whose ancestry should be searched- Returns:
- the nearest enclosing top-level container, or
null
-