eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll build a small Swing component that draws a quality circle, and layer in improvements for various requirements, such as centering, stroking, and accuracy for small sizes.

We’ll be relying on the official Java2D APIs and painting guidelines.

2. Project Structure

Let’s start by writing a class that extends JPanel to access the paintComponent() method. This integrates with the framework’s double buffering and ensures the background gets cleared before drawing:

public final class CirclePanel extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g.create();
        try {

        } finally {
            g2.dispose();
        }
    }
}

Based on the recommended pattern, we created a Graphics2D variable to handle the incoming Graphics, then we disposed of it to prevent leaks.

3. Drawing a Circle

While we can draw a circle with drawOval(x, y, w, h), Java2D’s shape APIs yield more predictable composable results. Therefore, let’s use Ellipse2D with equal width and height to represent a circle and pass it to the draw() and fill() methods:

double diameter = 160;
double x = 40;
double y = 40;
Shape circle = new Ellipse2D.Double(x, y, diameter, diameter);

g2.setPaint(new Color(0xB3E5FC));
g2.fill(circle);

g2.setPaint(new Color(0x01579B));
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.draw(circle);

To add some color to the circle, we can use setPaint() and pass a color, as well as setStroke() to see the outline better.

Running our code now will result in a decent circle, but far from what we want:

Circle without any improvements

Let’s enhance our circle by adding a few improvements. Specifically, we’ll adjust its size dynamically based on the window dimensions and center it:

float stroke = 2f;
int pad = 12;

double diameter = Math.min(getWidth(), getHeight()) - pad - stroke;
double cx = getWidth()  / 2.0;
double cy = getHeight() / 2.0;

double x = cx - diameter / 2.0;
double y = cy - diameter / 2.0;

Shape circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

By taking the smaller window dimension and subtracting padding, the code dynamically resizes the circle; then, it centers it by calculating the midpoint and positioning it accordingly.

As a result, the strokes extend halfway inside and halfway outside the shape’s bounds. By accounting for this, we prevent the outline from clipping in tight layouts:

Centered and resizable circle

While this looks a bit better, we’re still far from having a crisp-looking circle.

4. Quality Rendering Hints

Graphics2D gives us access to certain hints by using setRenderingHint().

First, we enable antialiasing to smooth the edges and remove the staircase effect on diagonals and curves:

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

Antialiasing alone already improves the quality a lot. However, when we draw very small circles or care about sub-pixel accuracy, we also enable pure stroke control:

g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

This hint tells Java2D to calculate stroke geometry in a device-independent way, which helps small, thin circles look more uniform at different positions and sizes.

We can further increase quality by adding a rendering hint:

g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

With the hints added, we can now see noticeable improvements to the circle, even at smaller window sizes:

Anti-aliasing and other hints enabled Small circle render

As we iterate, we can try different diameters, stroke widths, and placements. Because we’re using shapes, we can also apply transforms:

g2.translate(10, 10);
g2.scale(1.25, 1.25);

This way, we can test our circle in different circumstances.

5. Small Circles and Icons

At small icon sizes, 12 – 24 pixels, tiny rounding differences become more visible. We’ll often notice an outline that looks a bit thicker on one side. Even with antialiasing, pixels can’t represent perfect geometry at that scale.

To counter this, we can render the circle into a BufferedImage offscreen, apply high-quality hints, and then draw that image wherever we need it. This provides consistent results and saves CPU time when we reuse the same circle repeatedly.

There are two common ways to do this, depending on whether we want the highest possible smoothness or maximum runtime efficiency.

5.1. Supersampled Offscreen Rendering

In this approach, we draw the circle at a larger resolution, typically 2× or 3× the final size, and then scale it down when painting:

BufferedImage makeSupersampledCircle(int finalSize, int scale, float stroke) {
    int hi = finalSize * scale;
    BufferedImage img = new BufferedImage(hi, hi, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = img.createGraphics();
    try {
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

        double d = hi - stroke;
        Shape circle = new Ellipse2D.Double(stroke / 2.0, stroke / 2.0, d, d);

        g2.setPaint(new Color(0xBBDEFB));
        g2.fill(circle);
        g2.setPaint(new Color(0x0D47A1));
        g2.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g2.draw(circle);
    } finally {
        g2.dispose();
    }
    return img;
}

This technique, called supersampling, effectively performs an extra level of antialiasing during the image resampling, producing smooth edges.

To use it, we draw the large image scaled down inside paintComponent():

g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.drawImage(hiResImage, x, y, finalSize, finalSize, null);

This extra resampling pass hides pixel jaggies that even Java2D’s antialiasing can’t smooth out on tiny circles:

Circle drawn using supersampling

The trade-off is slightly higher memory and CPU usage, but it’s the technique for producing crisp badge icons, status lights, or toolbar dots.

5.2. Hardware Compatible BufferedImage

For speed and simplicity, we render the circle directly at its final size using a hardware-compatible transparent image:

BufferedImage makeCircleBadge(int size, float stroke) {
    GraphicsConfiguration gc = GraphicsEnvironment
      .getLocalGraphicsEnvironment()
      .getDefaultScreenDevice()
      .getDefaultConfiguration();

    BufferedImage img = gc.createCompatibleImage(size, size, Transparency.TRANSLUCENT);
    Graphics2D g2 = img.createGraphics();
    try {
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

        double d = size - stroke;
        Shape circle = new Ellipse2D.Double(stroke / 2.0, stroke / 2.0, d, d);

        g2.setPaint(new Color(0xBBDEFB));
        g2.fill(circle);

        g2.setPaint(new Color(0x0D47A1));
        g2.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g2.draw(circle);
    } finally {
        g2.dispose();
    }
    return img;
}

This approach uses createCompatibleImage() so the resulting bitmap matches our display’s color model and can be drawn very efficiently.

This method produces a clean icon with a transparent background. Because the image format is optimized for the GPU, drawing it repeatedly in tables, buttons, or dashboards is very fast:

Buffered circle draw

If we cache the image and reuse it, the UI stays responsive even when we have hundreds of small circular indicators.

We can even combine the two methods, render supersampled images once at startup and reuse the downscaled bitmaps throughout the UI for the best of both worlds.

6. Conclusion

In this article, we explored several ways to draw a decent-looking circle in Java.

We saw how proper use of Graphics2D, antialiasing, and rendering hints can produce smooth, symmetric results. We learned how offscreen rendering with BufferedImage, either supersampled or hardware-compatible, helps create crisp, small icons. With these techniques, it’s easy to render circles that look clean and consistent across all Java applications.

As always, the code can be found over on GitHub.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments