Drawing with Java 2D: Shapes, Colors, Fonts and Images
Painting Swing components with Graphics2D: the Rectangle2D/Ellipse2D/Line2D shape classes and their Float and Double versions, draw versus fill, colors, alpha and gradients, logical fonts and text metrics for centering strings, and loading, scaling and tiling images.
kvi5hnuCode Sprout team member12 min readOn this page
Article 88 showed where drawing happens: in the paintComponent method of a component. This article covers what you can draw there with the Java 2D API: geometric shapes, colors and gradients, text in different fonts, and images. Exactly the same calls work when you draw into an image in memory, which is how the demo of this article, and server-side chart and thumbnail generation, work without a screen.
Graphics2D
paintComponent receives a Graphics parameter. Since Java 1.2 that object is always a Graphics2D, a subclass with a much richer API, so the first line of most painting code is a cast:
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g;
...
}
The old Graphics methods such as drawRect(int, int, int, int) and fillOval still work, but they take integer coordinates and each shape needs its own method. Java 2D instead represents shapes as objects and draws any of them with two methods: g2.draw(shape) traces the outline and g2.fill(shape) paints the interior.
Shape classes
Every geometric shape implements the java.awt.Shape interface. The most common ones in java.awt.geom:
| Class | Constructed from |
|---|---|
Line2D | start and end point |
Rectangle2D | top-left corner, width, height |
RoundRectangle2D | rectangle plus corner arc width and height |
Ellipse2D | its bounding rectangle |
Arc2D | bounding rectangle, start angle, extent, closure type |
QuadCurve2D, CubicCurve2D | end points and control points |
Path2D | any sequence of moveTo, lineTo, curveTo, closePath |
Point2D is not a shape but is used to build them. Article 102 covers curves, paths and combining shapes with Area.
Float and Double
Java 2D computes with floating-point coordinates, so shapes can sit between pixels and be scaled smoothly. Each class comes in two concrete versions, nested inside the abstract class: Rectangle2D.Float and Rectangle2D.Double, Point2D.Float and Point2D.Double, and so on. The only difference is how the numbers are stored. Accessors such as getWidth() return double in both, so the Double versions are the convenient default (no F suffixes or casts); the Float versions save memory when you create very many shapes.
var rect = new Rectangle2D.Double(10, 25, 22.5, 20); // x, y, width, height
var point = new Point2D.Double(10, 20);
The nested-class arrangement is only a naming trick to avoid names like DoubleRectangle2D.
Rectangular shapes and the legacy classes
Rectangle2D, RoundRectangle2D, Ellipse2D and Arc2D share the superclass RectangularShape, because each is defined by a bounding rectangle. It supplies more than twenty methods, including getX, getY, getWidth, getHeight, getCenterX, getCenterY, getMinX, getMaxX, getMinY, getMaxY, setFrame and setFrameFromCenter. There is no getCenter() returning a point; combine getCenterX() and getCenterY().
An ellipse's constructor takes the bounding rectangle, which is awkward when you know the center. Use setFrameFromCenter(centerX, centerY, cornerX, cornerY) with any corner of the bounding box:
var circle = new Ellipse2D.Double();
circle.setFrameFromCenter(cx, cy, cx + radius, cy + radius);
The integer classes from Java 1.0, java.awt.Rectangle and java.awt.Point, were later fitted into the hierarchy: they extend Rectangle2D and Point2D, so they can be passed wherever a shape or point is expected.
Shapes are pure geometry, useful even when nothing is drawn: contains(x, y) tests a point (hit testing for mouse clicks), intersects(rect) tests overlap, getBounds2D() gives the bounding box, and Point2D.distance measures distances.
draw versus fill
Drawing with a one-pixel pen and filling cover slightly different pixels. draw traces the outline of a 10×5 rectangle at (1, 1) through the pixels from x = 1 to x = 11 and y = 1 to y = 6, so the outline is 11 pixels wide and 6 high. fill covers exactly the area inside, 10×5 pixels, one fewer to the right and bottom. The demo shows both. When outlines and fills must line up, account for this difference, or use a BasicStroke (article 103).
Colors
g2.setPaint(paint) selects the paint for all following draw, fill and drawString calls. The simplest paint is a solid java.awt.Color:
- Thirteen constants:
BLACK,BLUE,CYAN,DARK_GRAY,GRAY,GREEN,LIGHT_GRAY,MAGENTA,ORANGE,PINK,RED,WHITE,YELLOW(lowercase aliases also exist). - Custom colors from red, green and blue components between 0 and 255:
new Color(0, 128, 128), or from a packed valuenew Color(0x2563EB), orColor.decode("#2563EB"). - A fourth alpha component sets transparency:
new Color(255, 0, 0, 128)is half-transparent red, blended with what is underneath. brighter(),darker(), and conversion to and from hue/saturation/brightness withColor.RGBtoHSBandColor.getHSBColor.
Color is one implementation of the Paint interface. Others fill shapes with gradients (GradientPaint, LinearGradientPaint, RadialGradientPaint) or a repeated image (TexturePaint). The older setColor method accepts only colors.
A component's setBackground and setForeground set its default colors. JComponent does not paint its background automatically; JPanel and other opaque components do, when super.paintComponent(g) is called at the start of their painting method.
Text and fonts
g2.drawString(text, x, y) draws a string in the current font and paint. Note that (x, y) is the start of the baseline, not the top-left corner.
Choosing a font
A Font is identified by a name, a style and a point size:
var font = new Font(Font.SANS_SERIF, Font.BOLD, 14);
g2.setFont(font);
The style is Font.PLAIN, Font.BOLD, Font.ITALIC, or Font.BOLD | Font.ITALIC. A point is 1/72 inch. The name can be a font face name such as "Helvetica Bold", a family name such as "Helvetica", or one of five logical font names that exist on every Java installation and map to real fonts on each system: Serif, SansSerif, Monospaced, Dialog and DialogInput (constants Font.SERIF, Font.SANS_SERIF, Font.MONOSPACED, Font.DIALOG, Font.DIALOG_INPUT). Physical fonts differ from machine to machine; list them with GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(). Older JDKs bundled the Lucida fonts; OpenJDK builds today rely on the fonts installed in the operating system.
To ship a specific typeface with your application, load it from a TrueType or OpenType file with Font.createFont(Font.TRUETYPE_FONT, inputStream) and derive sizes with deriveFont(24f). font.deriveFont(Font.ITALIC) similarly gives a variant of an existing font.
Measuring text
To center a string, or to draw a box around it, you need its size, which depends on the font, the text and the rendering device. Typesetting terms:

Get the device information as a FontRenderContext from the graphics object and ask the font for the bounds of the string:
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(message, context);
double width = bounds.getWidth();
double height = bounds.getHeight(); // ascent + descent + leading
double ascent = -bounds.getY(); // the rectangle starts at the baseline, so y is negative
font.getLineMetrics(message, context) returns a LineMetrics with getAscent(), getDescent(), getLeading() and getHeight(). Outside paintComponent, where no Graphics2D is available, use component.getFontMetrics(font); the older FontMetrics class offers stringWidth, getAscent and getHeight with integer results.
This program centers a message in its component and draws the baseline and the bounding box around it, so you can see that the calculation is exact:
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
public class CenteredText {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
var frame = new JFrame("Centered Text");
frame.add(new CenteredTextComponent("Hello, Java 2D!"));
frame.pack();
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class CenteredTextComponent extends JComponent {
private static final long serialVersionUID = 1L;
private final String message;
CenteredTextComponent(String message) { this.message = message; }
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
var font = new Font(Font.SERIF, Font.BOLD, 36);
g2.setFont(font);
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(message, context);
// (x, y) is where the baseline starts; bounds.getY() is minus the ascent
double x = (getWidth() - bounds.getWidth()) / 2;
double ascent = -bounds.getY();
double y = (getHeight() - bounds.getHeight()) / 2 + ascent;
g2.setPaint(new Color(0x1E3A8A));
g2.drawString(message, (int) x, (int) y);
g2.setPaint(Color.LIGHT_GRAY);
g2.draw(new Line2D.Double(x, y, x + bounds.getWidth(), y)); // baseline
g2.draw(new Rectangle2D.Double(x, y + bounds.getY(), bounds.getWidth(), bounds.getHeight()));
}
@Override public Dimension getPreferredSize() { return new Dimension(420, 160); }
}
The two rendering hints turn on antialiasing, which smooths the edges of shapes and text by blending edge pixels with the background. Swing's own components use the desktop's text antialiasing settings automatically; for your own drawing, set the hints explicitly.
Images
Reading an image file takes one line. The classic way uses ImageIcon, which loads the image completely before returning:
Image image = new ImageIcon("logo.png").getImage();
javax.imageio.ImageIO.read(file) (also for URLs and streams) returns a BufferedImage, whose pixels you can read and change, and ImageIO.write(image, "png", file) saves one. Standard formats are PNG, JPEG, GIF, BMP, WBMP and TIFF. Article 104 goes deeper.
Draw an image with drawImage:
g.drawImage(image, x, y, null); // natural size
g.drawImage(image, x, y, width, height, null); // scaled
The last parameter is an ImageObserver, which was notified about the progress of slowly loading images in the early days of Java. With fully loaded images, pass null.
To tile a component with an image, you can draw it once and then copy that area of pixels with g.copyArea(x, y, width, height, dx, dy), where dx and dy give the offset of the copy. Drawing the image repeatedly in a loop is equally simple and works on every kind of graphics target.
You can also draw into an image: bufferedImage.createGraphics() returns a Graphics2D for it. Call dispose() when you are finished with a graphics object you created yourself (never on the one Swing passes to paintComponent).
The program
The demo runs headless and paints into BufferedImages, printing them one character per pixel (# for black, o for other colors, . for white). It explores shapes as geometry, compares draw and fill, paints a component with a rectangle, its inscribed ellipse and a diagonal (antialiasing off, so the pixels are exact), works with colors, transparency and a gradient, checks the font-metric relationships, and writes, reloads, tiles and scales an image. Fonts and their exact pixel sizes differ between computers, so the font section prints only relationships that hold everywhere.
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.nio.file.*;
import java.util.*;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Solution {
static BufferedImage canvas(int w, int h) {
var img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setPaint(Color.WHITE);
g.fillRect(0, 0, w, h);
g.dispose();
return img;
}
/** One character per pixel: '#' black, 'o' other non-white, '.' white. */
static void ascii(BufferedImage img) {
for (int y = 0; y < img.getHeight(); y++) {
var sb = new StringBuilder();
for (int x = 0; x < img.getWidth(); x++) {
int rgb = img.getRGB(x, y) & 0xFFFFFF;
sb.append(rgb == 0 ? '#' : rgb == 0xFFFFFF ? '.' : 'o');
}
System.out.println(sb);
}
}
static int countNonWhite(BufferedImage img) {
int n = 0;
for (int y = 0; y < img.getHeight(); y++)
for (int x = 0; x < img.getWidth(); x++)
if ((img.getRGB(x, y) & 0xFFFFFF) != 0xFFFFFF) n++;
return n;
}
/** A component like the ones you put in a frame; here we paint it into an image. */
static class ShapesComponent extends JComponent {
private static final long serialVersionUID = 1L;
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g;
var rect = new Rectangle2D.Double(8, 3, 30, 14);
g2.setPaint(Color.BLACK);
g2.draw(rect);
var ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect); // ellipse inscribed in the rectangle
g2.setPaint(Color.BLUE);
g2.draw(ellipse);
g2.setPaint(Color.BLACK);
g2.draw(new Line2D.Double(rect.getMinX(), rect.getMinY(), rect.getMaxX(), rect.getMaxY()));
}
@Override public Dimension getPreferredSize() { return new Dimension(46, 21); }
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
System.out.println("== Shape objects are geometry, not pixels ==");
var rect = new Rectangle2D.Double(10, 25, 22.5, 20);
System.out.println("rect: x=" + rect.getX() + " y=" + rect.getY() + " w=" + rect.getWidth() + " h=" + rect.getHeight()
+ " center=(" + rect.getCenterX() + ", " + rect.getCenterY() + ") max=(" + rect.getMaxX() + ", " + rect.getMaxY() + ")");
var circle = new Ellipse2D.Double();
circle.setFrameFromCenter(rect.getCenterX(), rect.getCenterY(), rect.getCenterX() + 15, rect.getCenterY() + 15);
System.out.println("circle around the center: " + circle.getBounds2D());
System.out.println("circle contains center? " + circle.contains(rect.getCenterX(), rect.getCenterY())
+ " contains (rect corner)? " + circle.contains(rect.getX(), rect.getY())
+ " intersects rect? " + circle.intersects(rect));
var floatRect = new Rectangle2D.Float(10.0F, 25.0F, 22.5F, 20.0F);
System.out.println("Float and Double versions equal: " + floatRect.equals(rect) + ", getWidth() returns double: " + floatRect.getWidth());
var legacy = new Rectangle(10, 25, 22, 20);
System.out.println("java.awt.Rectangle is a Rectangle2D: " + (legacy instanceof Rectangle2D)
+ ", Point is a Point2D: " + (new Point(1, 2) instanceof Point2D));
System.out.println("distance (0,0)-(3,4): " + new Point2D.Double(0, 0).distance(new Point2D.Double(3, 4)));
System.out.println("\n== draw() vs fill() of the same 10 x 5 rectangle ==");
for (boolean fill : new boolean[] {false, true}) {
BufferedImage img = canvas(14, 8);
Graphics2D g = img.createGraphics();
g.setPaint(Color.BLACK);
var r = new Rectangle2D.Double(1, 1, 10, 5);
if (fill) g.fill(r); else g.draw(r);
g.dispose();
System.out.println((fill ? "fill" : "draw") + ": " + countNonWhite(img) + " pixels");
ascii(img);
}
System.out.println("\n== A component painting rectangle, inscribed ellipse (o = blue) and diagonal ==");
var comp = new ShapesComponent();
comp.setSize(comp.getPreferredSize());
BufferedImage shot = canvas(46, 21);
Graphics2D g = shot.createGraphics();
comp.paint(g);
g.dispose();
ascii(shot);
System.out.println("\n== Colors ==");
var teal = new Color(0, 128, 128);
System.out.printf("teal = #%06X, brighter #%06X, darker #%06X%n", teal.getRGB() & 0xFFFFFF,
teal.brighter().getRGB() & 0xFFFFFF, teal.darker().getRGB() & 0xFFFFFF);
Color brand = Color.decode("#2563EB");
float[] hsb = Color.RGBtoHSB(brand.getRed(), brand.getGreen(), brand.getBlue(), null);
System.out.printf("#2563EB = rgb(%d, %d, %d), hue %.0f deg, saturation %.0f%%, brightness %.0f%%%n",
brand.getRed(), brand.getGreen(), brand.getBlue(), hsb[0] * 360, hsb[1] * 100, hsb[2] * 100);
var halfRed = new Color(255, 0, 0, 128);
BufferedImage blend = canvas(1, 1);
Graphics2D bg = blend.createGraphics();
bg.setPaint(halfRed);
bg.fillRect(0, 0, 1, 1);
bg.dispose();
System.out.printf("50%% red over white gives #%06X%n", blend.getRGB(0, 0) & 0xFFFFFF);
BufferedImage grad = canvas(11, 1);
Graphics2D gg = grad.createGraphics();
gg.setPaint(new GradientPaint(0, 0, Color.BLACK, 10, 0, Color.WHITE));
gg.fillRect(0, 0, 11, 1);
gg.dispose();
var greys = new ArrayList<Integer>();
for (int x = 0; x <= 10; x += 5) greys.add(grad.getRGB(x, 0) & 0xFF);
System.out.println("gradient black->white, red channel at x=0,5,10: " + greys);
System.out.println("13 named constants include ORANGE " + Color.ORANGE.getRed() + "," + Color.ORANGE.getGreen() + "," + Color.ORANGE.getBlue());
System.out.println("\n== Fonts and text metrics ==");
try {
var font = new Font(Font.SANS_SERIF, Font.BOLD, 14);
System.out.println("logical name: " + font.getName() + ", bold: " + font.isBold() + ", size: " + font.getSize() + " pt");
Graphics2D tg = canvas(1, 1).createGraphics();
FontRenderContext frc = tg.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds("Hello, World!", frc);
LineMetrics lm = font.getLineMetrics("Hello, World!", frc);
System.out.println("bounds start at the baseline, so y = -ascent: " + (Math.abs(bounds.getY() + lm.getAscent()) < 0.01));
System.out.println("height = ascent + descent + leading: "
+ (Math.abs(bounds.getHeight() - (lm.getAscent() + lm.getDescent() + lm.getLeading())) < 0.01));
System.out.println("wider text, wider bounds: "
+ (font.getStringBounds("Hello, World!!", frc).getWidth() > bounds.getWidth()));
System.out.println("bold 14pt is larger than plain 10pt: "
+ (bounds.getHeight() > new Font(Font.SANS_SERIF, Font.PLAIN, 10).getStringBounds("Hello, World!", frc).getHeight()));
tg.dispose();
String[] families = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
System.out.println("logical families always available: "
+ Arrays.asList(families).containsAll(List.of("Dialog", "DialogInput", "Monospaced", "SansSerif", "Serif")));
} catch (Exception | Error e) { // a server image without any fonts installed
System.out.println("no fonts available here: " + e);
}
System.out.println("\n== Images: write, read back, draw scaled, tile with copyArea ==");
BufferedImage tile = canvas(4, 4);
Graphics2D tg2 = tile.createGraphics();
tg2.setPaint(Color.BLACK);
tg2.fillRect(0, 0, 2, 2);
tg2.fillRect(2, 2, 2, 2);
tg2.dispose();
Path png = Files.createTempFile("tile", ".png");
try {
ImageIO.write(tile, "png", png.toFile());
Image loaded = new ImageIcon(png.toString()).getImage(); // the classic way to load an image
BufferedImage viaImageIO = ImageIO.read(png.toFile()); // the more flexible way
System.out.println("ImageIcon size " + loaded.getWidth(null) + "x" + loaded.getHeight(null)
+ ", ImageIO size " + viaImageIO.getWidth() + "x" + viaImageIO.getHeight());
BufferedImage screen = canvas(24, 8);
Graphics2D sg = screen.createGraphics();
sg.drawImage(loaded, 0, 0, null); // once, at natural size
for (int i = 1; i * 4 < 24; i++) // tile the row by copying pixels
sg.copyArea(0, 0, 4, 4, i * 4, 0);
sg.drawImage(loaded, 0, 4, 8, 4, null); // scaled to 8 x 4
sg.dispose();
ascii(screen);
System.out.println("formats ImageIO can write include png, jpeg, gif, bmp, tiff, wbmp: "
+ Set.of(ImageIO.getWriterFormatNames()).containsAll(Set.of("png", "jpeg", "gif", "bmp", "tiff", "wbmp")));
} finally {
Files.delete(png);
}
}
}
== Shape objects are geometry, not pixels ==
rect: x=10.0 y=25.0 w=22.5 h=20.0 center=(21.25, 35.0) max=(32.5, 45.0)
circle around the center: java.awt.geom.Rectangle2D$Double[x=6.25,y=20.0,w=30.0,h=30.0]
circle contains center? true contains (rect corner)? false intersects rect? true
Float and Double versions equal: true, getWidth() returns double: 22.5
java.awt.Rectangle is a Rectangle2D: true, Point is a Point2D: true
distance (0,0)-(3,4): 5.0
== draw() vs fill() of the same 10 x 5 rectangle ==
draw: 30 pixels
..............
.###########..
.#.........#..
.#.........#..
.#.........#..
.#.........#..
.###########..
..............
fill: 50 pixels
..............
.##########...
.##########...
.##########...
.##########...
.##########...
..............
..............
== A component painting rectangle, inscribed ellipse (o = blue) and diagonal ==
..............................................
..............................................
..............................................
........##########ooooooooooo##########.......
........#.##..oooo...........oooo.....#.......
........#...##...................oo...#.......
........#..o..##...................o..#.......
........#oo.....##..................oo#.......
........#o........##.................o#.......
........o...........##................o.......
........o.............###.............o.......
........o................##...........o.......
........#o.................##........o#.......
........#oo..................##.....oo#.......
........#..o...................##..o..#.......
........#...oo...................##...#.......
........#.....oooo...........oooo..##.#.......
........##########ooooooooooo##########.......
..............................................
..............................................
..............................................
== Colors ==
teal = #008080, brighter #00B6B6, darker #005959
#2563EB = rgb(37, 99, 235), hue 221 deg, saturation 84%, brightness 92%
50% red over white gives #FF7F7F
gradient black->white, red channel at x=0,5,10: [0, 127, 254]
13 named constants include ORANGE 255,200,0
== Fonts and text metrics ==
logical name: SansSerif, bold: true, size: 14 pt
bounds start at the baseline, so y = -ascent: true
height = ascent + descent + leading: true
wider text, wider bounds: true
bold 14pt is larger than plain 10pt: true
logical families always available: true
== Images: write, read back, draw scaled, tile with copyArea ==
ImageIcon size 4x4, ImageIO size 4x4
##..##..##..##..##..##..
##..##..##..##..##..##..
..##..##..##..##..##..##
..##..##..##..##..##..##
####....................
####....................
....####................
....####................
formats ImageIO can write include png, jpeg, gif, bmp, tiff, wbmp: true
Points to notice:
- The circle centered on the rectangle contains the center but not the rectangle's corner, yet the two shapes still intersect.
- The drawn outline covers 30 pixels, the fill 50; the fill stops one pixel short on the right and bottom.
- Half-transparent red over white produced
#FF7F7F: each channel is blended halfway towards white. - The gradient ends at 254 instead of 255 because the color is sampled at pixel centers.
Common questions
Why does my drawing disappear when I resize or minimize the window?
You drew outside paintComponent, for example with getGraphics() in a listener. Swing repaints from scratch whenever needed, so all drawing must happen in paintComponent, based on the component's state. Change the state, then call repaint().
How do I get smooth lines and text?
Set RenderingHints.KEY_ANTIALIASING to VALUE_ANTIALIAS_ON and KEY_TEXT_ANTIALIASING to VALUE_TEXT_ANTIALIAS_ON on the Graphics2D at the start of paintComponent.
How do I center text exactly?
Measure with font.getStringBounds(text, g2.getFontRenderContext()) for the width and getLineMetrics for the ascent, then compute x = (width − textWidth) / 2 and baseline y = (height − textHeight) / 2 + ascent, as the article's CenteredText program shows.
Why is my custom font not used?
Font.createFont returns a font of size 1; call deriveFont(24f). To make it available by name to Swing components, register it with GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font).
How do I save my drawing as a PNG?
Paint into a BufferedImage (image.createGraphics()), call dispose(), then ImageIO.write(image, "png", file). The same painting method can serve both the screen and the file if it takes a Graphics2D parameter.
API reference
| Class / method | Purpose |
|---|---|
Graphics2D.draw(shape), fill(shape) | Outline or fill any Shape. |
Rectangle2D.Double, Ellipse2D.Double, Line2D.Double, Point2D.Double (and .Float) | Basic shapes and points. |
RectangularShape.getCenterX/Y, getMinX/MaxX/MinY/MaxY, getWidth/Height, setFrame, setFrameFromCenter | Bounding-rectangle geometry. |
Shape.contains, intersects, getBounds2D; Point2D.distance | Geometry queries. |
setPaint(paint), Color(r, g, b [, a]), Color.decode, brighter, darker, RGBtoHSB | Colors. |
GradientPaint, LinearGradientPaint, RadialGradientPaint, TexturePaint | Other paints. |
Component.setBackground, setForeground | Default colors of a component. |
Font(name, style, size), deriveFont, Font.createFont | Fonts; logical names SERIF, SANS_SERIF, MONOSPACED, DIALOG, DIALOG_INPUT. |
GraphicsEnvironment.getAvailableFontFamilyNames() | Installed font families. |
setFont, drawString(s, x, y), getFontRenderContext() | Draw text at a baseline. |
Font.getStringBounds(s, frc), getLineMetrics(s, frc), JComponent.getFontMetrics(font) | Measure text. |
setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON) | Smooth edges. |
new ImageIcon(file).getImage(), ImageIO.read, ImageIO.write | Load and save images. |
drawImage(img, x, y [, w, h], observer), copyArea(x, y, w, h, dx, dy) | Draw, scale and copy pixels. |
BufferedImage.createGraphics(), Graphics.dispose() | Draw into an image. |
Summary
- Cast the
GraphicsinpaintComponenttoGraphics2Dand drawShapeobjects withdrawandfill. - Shapes come in
FloatandDoubleversions; preferDouble. Rectangles, ellipses and arcs shareRectangularShape; build ellipses around a center withsetFrameFromCenter. - Select colors and gradients with
setPaint; colors can be translucent through alpha. - Fonts have a name (preferably a logical one or a bundled font file), a style and a size. Measure text with
getStringBoundsandLineMetricsto position it;drawStringtakes the baseline position. - Load images with
ImageIconorImageIO, draw them withdrawImage, and render intoBufferedImages for off-screen or server-side drawing.
Practice Questions
1. Why does Java 2D have both Rectangle2D.Float and Rectangle2D.Double, and which should you use?
Both store the same rectangle, one with float fields and one with double fields; all accessors return double. Float halves the memory per shape, which matters only when you create very large numbers of shapes. Double avoids F suffixes and casts in your code, so it is the sensible default.
2. You fill a rectangle and then draw its outline with the same coordinates, but the outline sticks out one pixel on the right and bottom. Explain.
With the default one-pixel pen, draw traces the outline along the rectangle's edges, so it covers the pixels at x + width and y + height. fill covers only the interior, from x to x + width − 1 and y to y + height − 1. To make them line up, draw the outline of a rectangle one pixel smaller, or adjust the stroke.
3. A string drawn with g2.drawString("Total", 10, 10) is mostly cut off at the top. Why?
The coordinates in drawString give the start of the baseline, not the top-left corner. With y = 10, everything above the baseline (the ascent, typically 10 to 15 pixels for normal fonts) ends up above the component's top edge. Compute the position from the font metrics, for example y = top + ascent, where the ascent is -font.getStringBounds(...).getY().
4. Why do the docs recommend logical font names such as SansSerif rather than "Arial" or "Helvetica"?
Physical fonts are installed per machine: Arial is common on Windows, Helvetica on macOS, and Linux servers may have neither. If a requested face is missing, Java silently substitutes the Dialog font, so the layout changes unpredictably. Logical names are guaranteed to map to a suitable real font everywhere. If you need an exact typeface, bundle its file and load it with Font.createFont.
5. A server generates thumbnails with g.drawImage(original, 0, 0, 160, 120, null) and the results look jagged. How can it improve quality?
drawImage with scaling uses fast nearest-neighbor interpolation by default. Set g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR) (or BICUBIC) before drawing. For large reductions, scaling down in several halving steps gives better results than one big step. Also draw into a BufferedImage of a suitable type (for example TYPE_INT_RGB) and dispose the graphics object afterwards.
Previous: Java GUI Toolkits and Your First JFrame: AWT, Swing and JavaFX
Next: Event Handling in Swing: Listeners, Adapters and Actions
Related reading
- Java GUI Toolkits and Your First JFrame: AWT, Swing and JavaFX
- Public Key Encryption in Java: RSA, Hybrid Encryption and ML-KEM
- Symmetric Encryption in Java: AES-GCM, Key Generation and Cipher Streams
- Certificates in Java: keytool, Certificate Chains and Signing JAR Files
- Digital Signatures in Java: Signing and Verifying with RSA, EdDSA and ML-DSA

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.