How do I open a Swing window on the event dispatch thread in Java?

Use SwingUtilities.invokeLater() to create and show a Swing window on the event dispatch thread (EDT). Swing uses this thread to process events such as mouse clicks and to update the interface.

This example opens a window and prints whether the code that creates it is running on the EDT.

Source code

Save the following code as SwingEdtExample.java:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class SwingEdtExample {
    void main() {
        IO.println("main() on the EDT: "
                + SwingUtilities.isEventDispatchThread());

        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        IO.println("showWindow() on the EDT: "
                + SwingUtilities.isEventDispatchThread());

        JFrame frame = new JFrame("Hello, Swing!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JLabel("Welcome to Swing", SwingConstants.CENTER));
        frame.setSize(400, 240);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Hello Swing!

The window looks like the one in the previous example. The console messages show which thread runs each method.

Explanation

When you launch the program, main() runs outside the EDT. It schedules the showWindow() method with this line:

SwingUtilities.invokeLater(this::showWindow);

The method reference this::showWindow supplies the task. invokeLater() puts that task on Swing’s event queue and returns without waiting. The EDT runs the task when it reaches the front of the queue.

The showWindow() method creates the frame and label, adds the label to the frame, and makes the window visible. All of those steps run on the EDT. Calling showWindow() directly from main() would run those steps on the main thread instead.

SwingUtilities.isEventDispatchThread() checks the thread that is running the current code. It returns false in main() and true in showWindow().

Run the example

javac SwingEdtExample.java
java SwingEdtExample

The console prints:

main() on the EDT: false
showWindow() on the EDT: true

Keep work on the EDT short. A slow operation, such as downloading a file, can keep Swing from responding to clicks or repainting the window. Run slow work in the background and send interface updates back to the EDT.

How do I understand the DispatcherServlet in Spring MVC?

In the previous tutorial, we created our first Spring MVC application using Java configuration, Maven, and Apache Tomcat. We registered a DispatcherServlet, created a controller, and displayed a JSP page in the browser.

But what actually happens when a browser sends an HTTP request to a Spring MVC application? How does Spring MVC know which controller method to execute? How does it generate an HTML page or write data directly to the HTTP response?

In this tutorial, we will explore the DispatcherServlet and the components involved in processing HTTP requests. We will also create a simple application that allows us to observe the request-processing flow.

1. What is the DispatcherServlet?

The DispatcherServlet is the central servlet in Spring MVC. It receives incoming HTTP requests mapped to it and coordinates the components responsible for processing those requests.

It implements a design pattern known as the Front Controller Pattern.

Instead of creating a separate servlet for every application feature, Spring MVC uses a central servlet to delegate requests to the appropriate controllers.

For example, consider the following application endpoints:

GET /products
GET /customers
GET /orders

Each endpoint may be handled by a different controller. However, all these requests can enter the application through the same DispatcherServlet.

The DispatcherServlet does not contain the application’s business logic. Its responsibility is to coordinate request processing.

2. The Front Controller Pattern

The Front Controller Pattern provides a centralized entry point for handling requests in a web application.

Without a front controller, we might need to create and register multiple servlets manually:

/products  --> ProductServlet
/customers --> CustomerServlet
/orders    --> OrderServlet

With Spring MVC, the requests are handled through the DispatcherServlet:

DispatcherServlet

This approach allows Spring MVC to provide common functionality, such as request mapping, parameter conversion, exception handling, and response generation, without requiring developers to implement these features separately in every controller.

3. Main Components of the DispatcherServlet

The DispatcherServlet works with several components to process HTTP requests.

Component Responsibility
DispatcherServlet Coordinates request processing.
HandlerMapping Finds the handler associated with an HTTP request.
HandlerAdapter Executes the selected handler.
HandlerInterceptor Intercepts requests before and after handler execution.
Controller Processes application requests.
Model Holds data to be displayed by a view.
ViewResolver Resolves a logical view name into a view.
View Renders the response using model data.
HttpMessageConverter Reads and writes HTTP message bodies.
HandlerExceptionResolver Handles exceptions during request processing.

Let’s examine the most important components.

HandlerMapping

The HandlerMapping determines which handler should process an incoming request.

For annotation-based controllers, Spring MVC uses the RequestMappingHandlerMapping class.

Consider the following controller method:

@GetMapping("/hello")
public String hello() {
    return "hello";
}

When Spring MVC receives a GET request for /hello, the handler mapping identifies the hello() method as the appropriate handler.

HandlerAdapter

After finding the handler, the DispatcherServlet delegates its execution to a HandlerAdapter.

For annotation-based controllers, Spring MVC uses RequestMappingHandlerAdapter.

This component performs several tasks, including:

  • Resolving controller method arguments.
  • Converting request parameters into Java types.
  • Invoking the controller method.
  • Processing the method’s return value.

For example:

@GetMapping("/hello")
public String hello(Model model) {
    model.addAttribute("message", "Hello!");
    return "hello";
}

Spring MVC automatically provides the Model argument when invoking the method.

ViewResolver

A ViewResolver converts a logical view name into a view that can render the response.

For example, if a controller returns:

return "hello";

An InternalResourceViewResolver configured with a prefix of /WEB-INF/views/ and a suffix of .jsp resolves the view to:

/WEB-INF/views/hello.jsp

HttpMessageConverter

Not every Spring MVC request requires a view.

A controller method annotated with @ResponseBody can write its return value directly to the HTTP response.

@GetMapping("/message")
@ResponseBody
public String message() {
    return "Hello, Spring MVC!";
}

Spring MVC uses an appropriate HttpMessageConverter to write the returned value to the response body.

In this example, the StringHttpMessageConverter can write the returned string as plain text.

For Java objects, Spring MVC can use a JSON message converter when the necessary JSON library is available.

HandlerExceptionResolver

The HandlerExceptionResolver provides a mechanism for handling exceptions that occur during request processing.

For example, it can help Spring MVC convert an exception into an appropriate HTTP error response or an error view.

We will explore exception handling in more detail in a later tutorial.

4. Understanding the Request Processing Flow

A typical Spring MVC request that returns an HTML page follows these steps:

  1. The client sends an HTTP request.
  2. The servlet container forwards the request to the DispatcherServlet.
  3. The DispatcherServlet uses a HandlerMapping to find the appropriate controller method.
  4. The DispatcherServlet delegates handler execution to a HandlerAdapter.
  5. The controller processes the request and returns a logical view name.
  6. The DispatcherServlet uses a ViewResolver to resolve the view.
  7. The view renders the response using the model data.
  8. The response is returned to the client.

When a controller uses @ResponseBody, the handler adapter can write the response through an HTTP message converter. In this case, the view resolution and rendering steps are not required.

5. Creating the Example Application

To understand how these components work together, we will create a Spring MVC application with two endpoints:

  • /hello — returns an HTML page using a JSP view.
  • /message — returns a plain-text response.

We will also register a simple interceptor to observe the request-processing lifecycle.

This example uses the following technologies:

Technology Version
Java 25
Spring Framework 7.1.0
Jakarta Servlet API 6.1.0
Apache Tomcat 11.x
Apache Maven 3.9 or later

We will continue using traditional Spring MVC without Spring Boot.

6. Project Structure

Create a Maven project named spring-mvc-dispatcher.

The project has the following directory structure:

spring-mvc-dispatcher/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── org/kodejava/springmvc/
        │       ├── config/
        │       │   ├── WebConfig.java
        │       │   └── WebAppInitializer.java
        │       ├── controller/
        │       │   └── HelloController.java
        │       └── interceptor/
        │           └── RequestLoggingInterceptor.java
        └── webapp/
            └── WEB-INF/
                └── views/
                    └── hello.jsp

7. Configuring Maven

Create the following pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
             http://maven.apache.org/POM/4.0.0
             https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.kodejava</groupId>
    <artifactId>spring-mvc-dispatcher</artifactId>
    <version>1.0.0</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>7.1.0</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>spring-mvc-dispatcher</finalName>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.5.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The spring-webmvc dependency provides the Spring MVC infrastructure.

The Jakarta Servlet API uses the provided scope because Apache Tomcat provides the servlet implementation at runtime.

8. Registering the DispatcherServlet

Create the WebAppInitializer.java class.

package org.kodejava.springmvc.config;

import org.springframework.web.servlet.support
        .AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

When Tomcat starts the application, Spring’s servlet initialization mechanism discovers this class and registers the DispatcherServlet.

The getServletConfigClasses() method specifies the configuration class used by the servlet’s application context.

The getServletMappings() method maps the servlet to /.

This mapping allows the DispatcherServlet to handle our application endpoints while JSP requests can still be handled by the container’s JSP servlet.

9. Creating a Request Logging Interceptor

To observe request processing, we will implement the HandlerInterceptor interface.

Create the RequestLoggingInterceptor.java class.

package org.kodejava.springmvc.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.jspecify.annotations.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class RequestLoggingInterceptor
        implements HandlerInterceptor {

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) {

        System.out.println("[1] preHandle");

        System.out.printf(
                "    Request: %s %s%n",
                request.getMethod(),
                request.getRequestURI()
        );

        if (handler instanceof HandlerMethod method) {
            System.out.printf(
                    "    Handler: %s.%s()%n",
                    method.getBeanType().getSimpleName(),
                    method.getMethod().getName()
            );
        }

        return true;
    }

    @Override
    public void postHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            @Nullable ModelAndView modelAndView) {

        System.out.println("[3] postHandle");

        if (modelAndView != null) {
            System.out.println(
                    "    View: " + modelAndView.getViewName()
            );
        } else {
            System.out.println("    No ModelAndView");
        }
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            @Nullable Exception ex) {

        System.out.println("[4] afterCompletion");
        System.out.println(
                "    HTTP status: " + response.getStatus()
        );
    }
}

The HandlerInterceptor interface provides three callback methods.

preHandle()

The preHandle() method is called after Spring MVC selects a handler but before the handler is executed.

Returning true allows request processing to continue.

Returning false stops the normal handler execution chain.

postHandle()

The postHandle() method is called after successful handler execution.

For a controller that returns a view, this method is normally called before the view is rendered.

The ModelAndView argument contains the model and view information when available.

For a controller that writes directly to the response body, the argument is normally null.

afterCompletion()

The afterCompletion() method is called when request processing completes, provided the interceptor’s preHandle() method completed successfully and returned true.

This method is useful for cleanup and request logging.

In this example, we use System.out.println() to keep the code simple. Production applications should use a proper logging framework.

10. Configuring Spring MVC

Create the WebConfig.java class.

package org.kodejava.springmvc.config;

import org.kodejava.springmvc.interceptor.RequestLoggingInterceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("org.kodejava.springmvc.controller")
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        var resolver = new InternalResourceViewResolver();

        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");

        return resolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestLoggingInterceptor())
                .addPathPatterns("/hello", "/message");
    }
}

The @EnableWebMvc annotation enables Spring MVC infrastructure, including handler mappings, handler adapters, and message converters.

The viewResolver() method configures JSP view resolution.

The addInterceptors() method registers our custom interceptor for the /hello and /message endpoints.

The interceptor allows us to observe the request-processing lifecycle without modifying the DispatcherServlet itself.

11. Creating the Controller

Create the HelloController.java class.

package org.kodejava.springmvc.controller;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        System.out.println("[2] Controller: hello()");

        model.addAttribute(
                "message",
                "Hello from DispatcherServlet!"
        );

        return "hello";
    }

    @GetMapping(
            value = "/message",
            produces = MediaType.TEXT_PLAIN_VALUE
    )
    @ResponseBody
    public String message() {
        System.out.println("[2] Controller: message()");

        return "This response does not require a view.";
    }
}

The controller contains two methods that demonstrate different response-processing mechanisms.

The hello() method adds data to the model and returns a logical view name.

The message() method uses @ResponseBody to write a string directly to the HTTP response.

Although both methods return a String, Spring MVC processes their return values differently.

Method Return value interpretation
hello() Logical view name
message() HTTP response body

The @ResponseBody annotation is what makes the difference.

12. Creating the JSP View

Create the hello.jsp file under the src/main/webapp/WEB-INF/views directory.

<%@ page contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Spring MVC DispatcherServlet</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f8fafc;
            color: #1e293b;
            margin: 40px;
        }

        main {
            max-width: 640px;
            margin: 60px auto;
            padding: 32px;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
        }

        h1 {
            color: #2563eb;
        }

        code {
            background: #f1f5f9;
            padding: 3px 6px;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <main>
        <h1>${message}</h1>

        <p>
            This page is rendered using a JSP view.
        </p>

        <p>
            The request is processed by the
            <code>DispatcherServlet</code>.
        </p>
    </main>
</body>
</html>

The ${message} expression retrieves the model attribute provided by the controller.

Because the message is a fixed application-defined string, this example does not involve untrusted user input. When displaying user-provided values, make sure to escape the output appropriately.

13. Building and Running the Application

Open a terminal in the project directory and execute:

mvn clean package

After Maven completes the build, the generated WAR file is located at:

target/spring-mvc-dispatcher.war

Copy the WAR file into the webapps directory of Apache Tomcat 11.

On Linux or macOS:

cp target/spring-mvc-dispatcher.war \
   "$CATALINA_HOME/webapps/"

On Windows PowerShell:

Copy-Item target/spring-mvc-dispatcher.war `
    "$env:CATALINA_HOME\webapps\"

These commands assume that the CATALINA_HOME environment variable points to your Tomcat installation directory.

Start Tomcat in foreground mode so that you can observe the interceptor output directly in the terminal.

On Linux or macOS:

"$CATALINA_HOME/bin/catalina.sh" run

On Windows PowerShell:

& "$env:CATALINA_HOME\bin\catalina.bat" run

Make sure Tomcat is running with Java 25 because our application is compiled for Java 25.

14. Testing the HTML Response

Open your browser and visit:

http://localhost:8080/spring-mvc-dispatcher/hello

The browser should display:

Spring MVC Dispatcher

The Tomcat console should contain output similar to the following:

[1] preHandle
    Request: GET /spring-mvc-dispatcher/hello
    Handler: HelloController.hello()
[2] Controller: hello()
[3] postHandle
    View: hello
[4] afterCompletion
    HTTP status: 200

The output shows that Spring MVC has selected the hello() method before calling the interceptor’s preHandle() method.

The controller is then executed, followed by the postHandle() method.

After the JSP view has been rendered, the afterCompletion() method is called.

15. Testing the Plain-Text Response

Open the following URL:

http://localhost:8080/spring-mvc-dispatcher/message

The browser should display:

Plain-Text Response

The Tomcat console should contain output similar to the following:

[1] preHandle
    Request: GET /spring-mvc-dispatcher/message
    Handler: HelloController.message()
[2] Controller: message()
[3] postHandle
    No ModelAndView
[4] afterCompletion
    HTTP status: 200

Notice that the postHandle() method does not receive a ModelAndView object.

This happens because the controller uses @ResponseBody.

The handler adapter processes the return value using an HTTP message converter rather than returning a logical view name to the DispatcherServlet.

We can also test this endpoint using curl:

curl -i http://localhost:8080/spring-mvc-dispatcher/message

The response should be similar to:

HTTP/1.1 200
Content-Type: text/plain;charset=ISO-8859-1

This response does not require a view.

The actual response headers, including the character encoding, may vary depending on the Spring MVC and servlet container configuration.

16. Comparing View Rendering and Response Body Processing

Our application demonstrates two common ways of generating HTTP responses.

View Rendering and Response Body Processing

When a controller returns a logical view name, the processing flow includes view resolution and rendering.

When a controller uses @ResponseBody, the response is generated through an HTTP message converter during handler adapter execution.

Simplified DipatcherServlet Processing Flow

These diagrams are simplified. The DispatcherServlet coordinates the components rather than simply passing the request from one component to the next.

The important difference is that response body processing does not require a ViewResolver.

This mechanism is commonly used when building REST APIs.

17. What Happens When No Handler Is Found?

Try accessing an endpoint that does not exist:

http://localhost:8080/spring-mvc-dispatcher/unknown

The application should return an HTTP 404 response.

This happens because Spring MVC cannot find a handler for the requested path.

Similarly, sending a POST request to an endpoint that only supports GET normally produces an HTTP 405 response.

curl -i -X POST \
    http://localhost:8080/spring-mvc-dispatcher/hello

Expected HTTP status:

405 Method Not Allowed

These examples demonstrate that Spring MVC considers both the request path and the HTTP method when selecting a handler.

18. Summary

In this tutorial, we learned how the DispatcherServlet coordinates HTTP request processing in Spring MVC.

We explored the following concepts:

  • The Front Controller Pattern.
  • The role of the DispatcherServlet.
  • Finding controllers using HandlerMapping.
  • Executing controllers using HandlerAdapter.
  • Observing request processing using HandlerInterceptor.
  • Rendering HTML pages using ViewResolver.
  • Writing response bodies using HttpMessageConverter.
  • Understanding the difference between view names and response bodies.
  • Handling requests that do not match a controller.

Understanding the DispatcherServlet provides a strong foundation for learning more advanced Spring MVC features.

In the next tutorial, How do I configure Spring MVC using Java configuration?, we will explore WebMvcConfigurer, application context configuration, static resources, and other configuration options in more detail.

19. Maven Artifacts

The following Maven artifacts are required for this example.

Spring Web MVC

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>7.1.0</version>
</dependency>

Maven coordinates:

org.springframework:spring-webmvc:7.1.0

Jakarta Servlet API

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven coordinates:

jakarta.servlet:jakarta.servlet-api:6.1.0

Maven Compiler Plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.14.1</version>
</plugin>

Maven WAR Plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.5.0</version>
</plugin>

Other required Spring modules and JSpecify annotations are available through Spring’s transitive dependencies.

References

How do I implement the Prototype pattern in Java?

Suppose an application creates monthly sales reports with the same initial sections. A configured report can serve as a template. Each month, the application copies it, changes the title, and adds the sections needed for that month.

Prototype is a Gang of Four creational pattern that creates objects by copying an existing instance. The prototype carries the configuration from which new objects are produced. A client can request a copy through an interface while the concrete class implements its copying rules. GoF pattern catalog

This article completes our creational patterns series following Factory Method, Abstract Factory, and Builder. The series began with the existing Singleton example. Singleton pattern

A complete example

Save the following code as PrototypeExample.java. It uses standard Java APIs available in Java 8 and later.

package org.kodejava.pattern.prototype;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class PrototypeExample {
    interface Report {
        Report copy();
        void setTitle(String title);
        void addSection(String section);
    }

    static final class SalesReport implements Report {
        private String title;
        private final List<String> sections;

        SalesReport(String title, List<String> sections) {
            this.title = Objects.requireNonNull(title);
            this.sections = new ArrayList<>(sections);
        }

        private SalesReport(SalesReport original) {
            this(original.title, original.sections);
        }

        @Override
        public SalesReport copy() {
            return new SalesReport(this);
        }

        @Override
        public void setTitle(String title) {
            this.title = Objects.requireNonNull(title);
        }

        @Override
        public void addSection(String section) {
            sections.add(Objects.requireNonNull(section));
        }

        @Override
        public String toString() {
            return title + " " + sections;
        }
    }

    static Report customize(Report prototype) {
        Report report = prototype.copy();
        report.setTitle("November sales");
        report.addSection("Regional totals");
        return report;
    }

    public static void main(String[] args) {
        Report template = new SalesReport("Sales template",
                Arrays.asList("Summary", "Revenue"));
        Report november = customize(template);

        System.out.println("Template: " + template);
        System.out.println("Copy: " + november);
        System.out.println("Same instance: " + (template == november));

        november.addSection("Forecast");
        System.out.println("Template after edit: " + template);
        System.out.println("Copy after edit: " + november);
    }
}

Compile and run the example from the directory containing the source file.

javac -d out PrototypeExample.java
java -cp out org.kodejava.pattern.prototype.PrototypeExample

The program prints the original template and customized copy, then edits the copy again.

Template: Sales template [Summary, Revenue]
Copy: November sales [Summary, Revenue, Regional totals]
Same instance: false
Template after edit: Sales template [Summary, Revenue]
Copy after edit: November sales [Summary, Revenue, Regional totals, Forecast]

How copying works

GoF role Example Responsibility
Prototype Report Declares the copying operation used by the client.
Concrete prototype SalesReport Copies its title and sections according to its own rules.
Client customize() Obtains a copy through the interface and customizes it.
Configured prototype instance template in main() Supplies the initial report state.

The application creates the template once. The customize() method receives it through the Report interface and calls copy(). The concrete prototype returns a new SalesReport using a private copy constructor. Another report implementation could supply its own copying behavior through the same interface.

The false identity comparison shows that the template and copy are distinct report instances. Their section lists are also separate. The constructor creates a new ArrayList, so adding Regional totals or Forecast to the copy leaves the template’s sections intact.

The list elements are strings, which are immutable, so both lists can safely refer to the same section strings. If sections become mutable objects with their own fields, copying the list will still share those elements. The copy implementation must then decide which elements to duplicate and which references to share.

Choosing a copy policy

A useful copy contract states what the new object inherits and what becomes independent. In this example, the copy starts with the same title and section values, then owns its own mutable section list. A business object might also need a new identifier or a cleared creation timestamp.

Java provides Object.clone(), whose default behavior copies field values and shares referenced objects. This is a shallow copy. Our example exposes an explicit copy() method and constructs its result with the required list ownership. The Prototype pattern’s copying contract can be implemented this way. Object.clone() documentation

More elaborate object graphs require additional decisions. Shared subobjects, cycles, open resources, and external identities all affect what a valid copy means. Keep those decisions in the concrete prototype and document them for callers.

When should I use Prototype?

Prototype fits applications that repeatedly create objects from configured templates, particularly when client code works with multiple concrete types through a shared interface. A registry of named templates can let callers choose the starting configuration at runtime.

Copying also has a maintenance cost. When fields are added, review the copy operation so the new state receives the intended treatment. Copying large mutable graphs can consume substantial memory and time. Measure the actual construction and copying costs before choosing Prototype for performance.

For a small object with straightforward initialization, a constructor or factory can be sufficient. Prototype becomes useful when an existing instance provides the state needed to create another object.

Next, we begin structural patterns with Adapter.

How do I set up Project Lombok in a Java 25 Maven project?

Project Lombok generates common Java code during compilation. In this example, it generates getters and a setter for a Book class. You can call those methods from Java as soon as the project compiles.

Configure Maven

Use JDK 25 and Maven 3.9.x. Run mvn -v and check that Maven reports Java 25. Then create this pom.xml in the project root.

<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.kodejava</groupId>
    <artifactId>lombok-getting-started</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <lombok.version>1.18.44</lombok.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
                <configuration>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The provided dependency makes Lombok’s annotations available at compile time. The annotationProcessorPaths entry tells the compiler where to load Lombok’s annotation processor. With JDK 25, the dependency declaration alone does not activate annotation processing. The compiled example runs without the Lombok JAR.

Generate your first getter and setter

Create src/main/java/org/kodejava/lombok/Book.java.

package org.kodejava.lombok;

import lombok.Getter;
import lombok.Setter;

public class Book {
    @Getter
    private final String isbn;

    @Getter
    @Setter
    private String title;

    public Book(String isbn, String title) {
        this.isbn = isbn;
        this.title = title;
    }
}

@Getter generates getIsbn() and getTitle(). @Setter generates setTitle(String title). The ISBN is set in the constructor and remains fixed for the lifetime of the object.

Create src/main/java/org/kodejava/lombok/Main.java and call the generated methods.

package org.kodejava.lombok;

public class Main {
    public static void main(String[] args) {
        Book book = new Book("9780134685991", "Effective Java");
        System.out.println(book.getIsbn());
        System.out.println(book.getTitle());

        book.setTitle("Effective Java, Third Edition");
        System.out.println(book.getTitle());
    }
}

Compile and run

Run these commands from the directory containing pom.xml.

mvn clean compile
java -cp target/classes org.kodejava.lombok.Main

The program prints the ISBN, the original title, and the updated title.

9780134685991
Effective Java
Effective Java, Third Edition

If Maven compiles the example and your IDE still marks getTitle() as unresolved, check the IDE’s Lombok support and annotation processing settings, then reload the Maven project.

References

Maven artifact

The example uses org.projectlombok:lombok:1.18.44. Keep the dependency and annotation processor on the same Lombok version.

How do I create a window using JFrame in Java?

Use JFrame to create a Swing window with a title bar and an area for components. In this example, you will open a window with a centered welcome message.

Source code

Save the following code as JFrameExample.java:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class JFrameExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        JFrame frame = new JFrame("Hello, Swing!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel message = new JLabel(
                "Welcome to Swing", SwingConstants.CENTER);
        frame.add(message);

        frame.setSize(400, 240);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Hello Swing!

This illustration shows the layout. The title bar and window controls may look different on your operating system.

Explanation

new JFrame("Hello, Swing!") creates the window and sets its title. EXIT_ON_CLOSE tells Java to exit the application when you close this window.

The JLabel displays Welcome to Swing. SwingConstants.CENTER centers the text horizontally, and frame.add(message) places the label inside the window.

setSize(400, 240) sets the size of the entire window, including its border and title bar. Call setLocationRelativeTo(null) after setting the size to center the window on the screen. Finally, setVisible(true) displays it.

The main() method uses SwingUtilities.invokeLater(this::showWindow) to schedule window creation on Swing’s event dispatch thread. This is the thread Swing uses to handle events and update the interface.

Run the example

Compile and run the file:

javac JFrameExample.java
java JFrameExample

A window titled Hello, Swing! opens with the welcome message in the center. Close the window to end the program.