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

Illustration of a window titled Hello, Swing! with a centered Welcome to Swing message

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.

How do I send and receive JMS messages with Spring Boot?

When an application creates an order, it may also need to arrange shipping or send a confirmation email. A queue lets the application hand off that work. The application sends a message containing the order ID, and a consumer processes it asynchronously.

In this first article, you’ll send a message to the orders.created queue with JmsTemplate and receive it with @JmsListener. The example uses Java 25, Maven, Spring Boot 4.1.2, and Apache ActiveMQ Artemis.

What is JMS?

Java Message Service (JMS), now called Jakarta Messaging, defines a standard Java API for sending and receiving messages. Modern Spring applications use the jakarta.jms package. In this example, ActiveMQ Artemis is the message broker that manages the queue and delivers messages.

Component Role
Producer Sends a message announcing that order ORD-1001 was created.
Broker Accepts the message and delivers it to a consumer.
Queue Holds messages for delivery. If multiple consumers listen to the same queue, each delivery goes to one consumer, allowing them to share the work.
Consumer Receives the message from the queue and logs its contents.

Spring Boot configures the connection to Artemis and sets up the Spring JMS infrastructure. For this tutorial, Artemis runs as an embedded broker in the same Java process as the producer and consumer. You only need JDK 25 and Maven. Broker persistence is disabled, so any messages still in the queue are lost when the broker stops.

1. Create a Maven project

Save this configuration as pom.xml in the project directory.

<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>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.2</version>
        <relativePath/>
    </parent>

    <groupId>org.kodejava</groupId>
    <artifactId>spring-jms-week-01</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <java.version>25</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-artemis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>artemis-jakarta-server</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2. Configure the broker and queue

Create src/main/resources/application.properties.

spring.artemis.mode=embedded
spring.artemis.embedded.persistent=false
spring.artemis.embedded.queues=orders.created

The last property tells Spring Boot to create the orders.created queue when the embedded broker starts.

3. Send a message at startup

Create src/main/java/org/kodejava/jms/OrderMessagingApplication.java.

package org.kodejava.jms;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.core.JmsTemplate;

@SpringBootApplication
public class OrderMessagingApplication {
    static final String ORDERS_CREATED = "orders.created";

    public static void main(String[] args) {
        SpringApplication.run(OrderMessagingApplication.class, args);
    }

    @Bean
    CommandLineRunner sendOrderCreated(JmsTemplate jmsTemplate) {
        return args -> jmsTemplate.convertAndSend(ORDERS_CREATED, "ORD-1001");
    }
}

The CommandLineRunner sends one message each time the application starts. The first argument to convertAndSend() is the destination name, and the second is the payload. The default message converter turns the Java String into a JMS TextMessage.

4. Receive the message from the queue

Create src/main/java/org/kodejava/jms/OrderCreatedListener.java.

package org.kodejava.jms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
public class OrderCreatedListener {
    private static final Logger log =
            LoggerFactory.getLogger(OrderCreatedListener.class);

    @JmsListener(destination = OrderMessagingApplication.ORDERS_CREATED)
    public void onOrderCreated(String orderId) {
        log.info("Order created - orderId={}", orderId);
    }
}

Spring registers the method annotated with @JmsListener with a listener container. When Artemis delivers a message from the queue, Spring extracts the text from the TextMessage and passes it to the method as the orderId argument. The listener processes the message asynchronously.

5. Run the application and check the output

Run this command from the directory containing pom.xml.

mvn spring-boot:run

Look for this message in the application log.

Order created - orderId=ORD-1001

The listener writes this log entry after receiving the message, so it confirms that the message traveled through the broker and reached the consumer. Press Ctrl+C to stop the application.

In the next article, we’ll run Artemis in Docker and connect to it over the network. We’ll reuse the producer, the consumer, and the orders.created queue name.

References

Maven Artifacts

Artifact Purpose
org.springframework.boot:spring-boot-starter-parent:4.1.2 Provides the parent POM and manages dependency versions.
org.springframework.boot:spring-boot-starter-artemis Adds Spring JMS integration and the Artemis client.
org.apache.activemq:artemis-jakarta-server Provides the embedded Artemis broker.
org.springframework.boot:spring-boot-maven-plugin Runs the application with mvn spring-boot:run.

How do I draw 2D shapes using Graphics2D?

In the previous tutorial, How do I create a game window using Java Swing?, we learned how to create a game window using JFrame and a drawing area using JPanel. We also separated our application into three classes: Game, GameWindow, and GamePanel.

Now that we have a game window, it is time to learn how to draw different shapes.

Drawing is one of the most important parts of 2D game programming. Before we start working with images, sprites, and animations, we should understand how Java draws objects on the screen.

In this tutorial, we will learn how to use the Graphics2D class to draw lines, rectangles, circles, ellipses, and polygons. We will also explore colors, stroke styles, and antialiasing.

Finally, we will combine these techniques to draw a simple game character.

1. Understanding Graphics2D

Java provides the Graphics2D class as part of the Java 2D API.

The Graphics2D class extends Graphics and provides more advanced drawing capabilities.

Some of its features include:

  • Drawing geometric shapes.
  • Filling shapes with colors.
  • Controlling line thickness and style.
  • Applying antialiasing to improve visual quality.
  • Drawing text.
  • Transforming shapes using translation, rotation, and scaling.

In a Swing application, we normally perform custom drawing inside the paintComponent() method of a JPanel.

For example:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    try {
        g2d.setColor(Color.BLUE);
        g2d.fillRect(100, 100, 80, 80);
    } finally {
        g2d.dispose();
    }
}

In this example, we create a copy of the graphics context, set the drawing color to blue, and draw a filled rectangle.

We use g.create() because we want to make changes to the graphics context without affecting the original object provided by Swing.

The copied graphics context is released by calling dispose().

Important: Never call dispose() on the original Graphics object supplied to paintComponent().

2. Preparing the project

We will continue using the Maven project from Week 02.

Our project structure remains the same:

java-2d-game/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── org/
                └── kodejava/
                    └── game/
                        ├── Game.java
                        ├── GameWindow.java
                        └── GamePanel.java

We only need to modify the GamePanel class to experiment with different drawing operations.

The Game and GameWindow classes will remain mostly unchanged.

3. Drawing lines

Let’s start with the simplest shape: a line.

Java provides the drawLine() method to draw a line between two points.

g2d.drawLine(x1, y1, x2, y2);

The parameters represent:

  • x1, y1: The starting point.
  • x2, y2: The ending point.

For example:

g2d.setColor(Color.RED);
g2d.drawLine(50, 50, 250, 50);

This draws a horizontal red line from (50, 50) to (250, 50).

We can also draw a diagonal line:

g2d.setColor(Color.GREEN);
g2d.drawLine(50, 80, 250, 180);

Lines are useful for drawing boundaries, laser beams, grid systems, and other visual elements in games.

4. Drawing rectangles

Rectangles are among the most commonly used shapes in 2D games.

We can use rectangles to represent players, enemies, walls, platforms, and collision boundaries.

Java provides two important methods:

g2d.drawRect(x, y, width, height);
g2d.fillRect(x, y, width, height);

The difference is simple:

  • drawRect() draws only the outline.
  • fillRect() draws a filled rectangle.

For example:

g2d.setColor(Color.YELLOW);
g2d.drawRect(50, 220, 120, 80);

g2d.setColor(Color.BLUE);
g2d.fillRect(200, 220, 120, 80);

The first rectangle has a yellow outline.

The second rectangle is filled with blue.

Notice that both rectangles are positioned using the coordinates of their upper-left corners.

5. Drawing circles and ellipses

Java does not provide a separate drawCircle() method in the basic Graphics API.

Instead, we use drawOval() and fillOval().

g2d.drawOval(x, y, width, height);
g2d.fillOval(x, y, width, height);

When the width and height are equal, the shape is a circle.

For example:

g2d.setColor(Color.CYAN);
g2d.fillOval(50, 350, 80, 80);

This draws a filled circle with a diameter of 80 pixels.

To draw an ellipse, use different values for width and height:

g2d.setColor(Color.MAGENTA);
g2d.fillOval(180, 350, 140, 70);

Circles and ellipses are useful for drawing balls, planets, wheels, particles, and other rounded game objects.

6. Drawing polygons

A polygon is a shape created by connecting several points.

Examples include triangles, pentagons, and hexagons.

Java provides the drawPolygon() and fillPolygon() methods.

Let’s draw a triangle:

int[] xPoints = {400, 350, 450};
int[] yPoints = {350, 450, 450};

g2d.setColor(Color.ORANGE);

g2d.fillPolygon(
        xPoints,
        yPoints,
        3);

The arrays contain the horizontal and vertical coordinates of the triangle’s three corners.

The final argument tells Java how many points should be used.

Polygons are particularly useful for drawing spaceships, arrows, terrain, and other objects with irregular shapes.

7. Working with colors

So far, we have used predefined colors such as:

Color.RED
Color.GREEN
Color.BLUE
Color.YELLOW

Java also allows us to create custom colors using RGB values.

RGB stands for Red, Green, and Blue.

Each component normally ranges from 0 to 255.

For example:

Color skyBlue = new Color(135, 206, 235);
Color grassGreen = new Color(34, 139, 34);
Color darkBackground = new Color(15, 23, 42);

We can use these colors just like predefined colors:

g2d.setColor(skyBlue);
g2d.fillRect(0, 0, 800, 600);

Custom colors give us greater control over the visual appearance of our games.

Using transparency

We can also create colors with transparency.

The fourth parameter of the Color constructor represents the alpha value:

Color transparentBlue =
        new Color(0, 100, 255, 128);

An alpha value of 0 means fully transparent, while 255 means fully opaque.

Transparency is useful for drawing shadows, overlays, particles, and visual effects.

8. Controlling line thickness

The Graphics2D class allows us to customize how lines are drawn.

We can use the BasicStroke class to control line thickness.

For example:

g2d.setColor(Color.WHITE);
g2d.setStroke(new BasicStroke(5.0f));

g2d.drawLine(400, 50, 650, 50);

This draws a white line with a thickness of 5 pixels.

We can also customize the stroke used to draw a rectangle:

g2d.setStroke(new BasicStroke(3.0f));
g2d.drawRect(400, 100, 150, 100);

Stroke settings are useful for drawing borders, paths, and visual indicators.

Remember that a stroke setting remains active for subsequent drawing operations until it is changed.

Because our example uses a copied graphics context, changes will not affect Swing’s original graphics context.

9. Improving rendering with antialiasing

When we draw diagonal lines or circles, their edges may appear jagged.

This effect is sometimes called aliasing.

Antialiasing helps produce smoother edges by blending colors around shape boundaries.

We can enable it using a rendering hint:

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

This instructs Java 2D to use antialiasing when supported.

Antialiasing is especially useful when drawing circles, polygons, and curved shapes.

However, it also introduces additional rendering work.

For simple games, this is generally acceptable. Later, when we study performance optimization, we will explore how rendering choices affect game performance.

10. Creating a complete shapes demonstration

Now let’s combine everything we have learned into one program.

Replace the contents of GamePanel.java with the following code:

package org.kodejava.game;

import javax.swing.JPanel;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

public class GamePanel extends JPanel {

    public static final int GAME_WIDTH = 800;
    public static final int GAME_HEIGHT = 600;

    public GamePanel() {
        setPreferredSize(new Dimension(
                GAME_WIDTH, GAME_HEIGHT));

        setBackground(new Color(15, 23, 42));
        setDoubleBuffered(true);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g.create();

        try {
            g2d.setRenderingHint(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

            drawTitle(g2d);
            drawLines(g2d);
            drawRectangles(g2d);
            drawCircles(g2d);
            drawPolygons(g2d);
        } finally {
            g2d.dispose();
        }
    }

    private void drawTitle(Graphics2D g2d) {
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font(
                Font.SANS_SERIF, Font.BOLD, 24));

        g2d.drawString(
                "Java 2D Shapes",
                40, 45);
    }

    private void drawLines(Graphics2D g2d) {
        g2d.setColor(Color.RED);
        g2d.setStroke(new BasicStroke(3.0f));
        g2d.drawLine(50, 100, 250, 100);

        g2d.setColor(Color.GREEN);
        g2d.drawLine(50, 130, 250, 200);

        g2d.setStroke(new BasicStroke(1.0f));
    }

    private void drawRectangles(Graphics2D g2d) {
        g2d.setColor(Color.YELLOW);
        g2d.drawRect(350, 90, 120, 90);

        g2d.setColor(Color.BLUE);
        g2d.fillRect(500, 90, 120, 90);
    }

    private void drawCircles(Graphics2D g2d) {
        g2d.setColor(Color.CYAN);
        g2d.fillOval(50, 260, 100, 100);

        g2d.setColor(Color.MAGENTA);
        g2d.fillOval(200, 270, 160, 80);
    }

    private void drawPolygons(Graphics2D g2d) {
        int[] xPoints = {500, 440, 560};
        int[] yPoints = {260, 380, 380};

        g2d.setColor(Color.ORANGE);
        g2d.fillPolygon(xPoints, yPoints, 3);
    }
}

We have organized our drawing code into several methods.

Each method handles a specific group of shapes.

This makes the program easier to read and maintain compared to placing all drawing operations directly inside paintComponent().

It also allows us to extend the program more easily.

11. Creating the GameWindow class

Our GameWindow class is almost identical to the one from Week 02.

package org.kodejava.game;

import javax.swing.JFrame;

public class GameWindow extends JFrame {

    public GameWindow() {
        setTitle("KodeJava 2D Shapes");

        setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);

        setContentPane(new GamePanel());

        pack();
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }
}

The window uses our GamePanel as its content pane.

Because the panel defines its preferred size as 800 × 600 pixels, calling pack() creates a window with an appropriately sized drawing area.

12. Creating the Game class

The entry point remains simple:

package org.kodejava.game;

import javax.swing.SwingUtilities;

public class Game {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                GameWindow::new);
    }
}

We use SwingUtilities.invokeLater() to create the application on the Swing Event Dispatch Thread.

13. Running the program

Open a terminal in the project directory and compile the application:

mvn clean compile

Then run the application:

java -cp target/classes org.kodejava.game.Game

2D Shapes

You should see a window containing several geometric shapes on a dark background.

The demonstration includes two lines, an outlined rectangle, a filled rectangle, a circle, an ellipse, and a triangle.

Notice how the different drawing methods can be combined to create more complex visual objects.

14. Mini-project: Drawing a simple game character

Now that we understand basic shapes, let’s put them together to draw a simple character.

Our character will be a small robot made from rectangles, circles, and lines.

This approach is useful when we do not have image assets or sprites available.

Add the following method to GamePanel:

private void drawRobot(Graphics2D g2d) {
    int x = 350;
    int y = 200;

    // Robot body
    g2d.setColor(new Color(59, 130, 246));
    g2d.fillRoundRect(
            x, y + 60, 100, 120, 20, 20);

    // Robot head
    g2d.setColor(new Color(148, 163, 184));
    g2d.fillRoundRect(
            x + 10, y, 80, 70, 15, 15);

    // Eyes
    g2d.setColor(Color.CYAN);
    g2d.fillOval(x + 25, y + 20, 15, 15);
    g2d.fillOval(x + 60, y + 20, 15, 15);

    // Mouth
    g2d.setColor(Color.DARK_GRAY);
    g2d.fillRoundRect(
            x + 30, y + 48, 40, 8, 4, 4);

    // Arms
    g2d.setColor(new Color(100, 116, 139));
    g2d.fillRect(x - 20, y + 80, 20, 70);
    g2d.fillRect(x + 100, y + 80, 20, 70);

    // Legs
    g2d.fillRect(x + 20, y + 180, 20, 50);
    g2d.fillRect(x + 60, y + 180, 20, 50);

    // Antenna
    g2d.setStroke(new BasicStroke(4.0f));
    g2d.drawLine(
            x + 50, y,
            x + 50, y - 20);

    g2d.setColor(Color.RED);
    g2d.fillOval(x + 43, y - 30, 14, 14);
}

To display the robot instead of the shapes demonstration, update paintComponent() so that it calls drawRobot(g2d):

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    try {
        g2d.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        drawRobot(g2d);
    } finally {
        g2d.dispose();
    }
}

Drawing Robot Shape

The robot is made entirely from basic geometric shapes.

We use rounded rectangles for the body and head, circles for the eyes, rectangles for the arms and legs, and a line for the antenna.

Notice that the robot’s position is controlled by two variables:

int x = 350;
int y = 200;

The other coordinates are calculated relative to these values.

For example:

g2d.fillOval(x + 25, y + 20, 15, 15);

This places the left eye 25 pixels to the right and 20 pixels below the robot’s reference position.

If we change x or y, the entire robot moves because all its components use the same reference position.

This is an important concept in game programming.

Later in the series, we will use similar techniques to move players and enemies around the screen.

15. Understanding drawing order

One important rule in Java 2D is that drawing order matters.

When several shapes overlap, shapes drawn later appear on top of shapes drawn earlier.

For example:

g2d.setColor(Color.BLUE);
g2d.fillRect(100, 100, 100, 100);

g2d.setColor(Color.RED);
g2d.fillOval(125, 125, 50, 50);

The red circle appears on top of the blue rectangle because it is drawn afterward.

If we reverse these operations, the blue rectangle will cover the red circle.

This simple rule is useful when drawing backgrounds, characters, projectiles, and other objects.

A common rendering order for a simple game is:

  1. Background.
  2. Environment and platforms.
  3. Game objects.
  4. Player and enemies.
  5. User interface and overlays.

We will explore more advanced rendering techniques in future tutorials.

16. Try it yourself

Before moving to the next tutorial, practice the drawing techniques we have learned.

Exercise 1: Draw a house

Use rectangles, lines, and polygons to draw a simple house.

Try adding a roof, door, and two windows.

Exercise 2: Draw a traffic light

Draw a vertical rectangle containing three circles.

Use red, yellow, and green colors for the lights.

Exercise 3: Customize the robot

Modify the robot’s appearance by changing its colors, dimensions, and facial features.

Try adding hands or different-shaped feet.

Exercise 4: Move the robot

Change the values of x and y inside drawRobot().

Observe how all the robot’s parts move together.

As an additional challenge, try moving the robot’s position to the center of the game panel.

17. Summary

In this tutorial, we learned how to draw different shapes using the Java 2D API.

We covered:

  • Using Graphics2D for custom drawing.
  • Drawing lines with drawLine().
  • Drawing rectangles with drawRect() and fillRect().
  • Drawing circles and ellipses with drawOval() and fillOval().
  • Drawing polygons using arrays of coordinates.
  • Creating custom colors with RGB values.
  • Controlling line thickness using BasicStroke.
  • Improving visual quality using antialiasing.
  • Combining shapes to draw a simple game character.
  • Understanding how drawing order affects overlapping shapes.

We also created a simple robot character using only Java 2D drawing operations.

This demonstrates that we can create interesting game objects without using image files.

In the next tutorial, How do I understand coordinates in a 2D game?, we will explore the coordinate system in greater detail.

We will learn how to position objects, calculate distances, work with relative coordinates, and understand how coordinates affect game movement.

Maven Dependencies

Java Swing and the Java 2D API are included in the Java Development Kit.

No external dependencies are required for this tutorial.

Our Maven project uses Java 25 and the Maven Compiler Plugin.

Here is the complete pom.xml:

<?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>java-2d-game</artifactId>
    <version>1.0-SNAPSHOT</version>

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

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

Required Maven dependencies: None.

Build plugin:

org.apache.maven.plugins:maven-compiler-plugin:3.14.1

References

How Do I Display Tasks in a LazyColumn with Jetpack Compose?

In article 2, you created a Task model and three sample tasks. The screen displayed only the first task. In this article, you will display the entire collection as a scrolling list and create a reusable component for each task.

Continue with the same Task Notes project, package org.kodejava.tasknotes, and generated TaskNotesTheme. Keep Task.kt and SampleTasks.kt from the previous article unchanged.

1. Choose a layout for the list

Column arranges composables vertically. LazyColumn provides a vertically scrolling list whose items are composed and laid out as needed. It also supports prefetching, so avoid assuming that only the exact visible rows can exist in composition.

Three fixed rows could fit in a regular Column. We use LazyColumn because Task Notes will eventually contain a growing collection of user-created tasks. See the official lazy lists documentation.

We will keep the screen title above the list so that it remains visible while the tasks scroll.

2. Replace MainActivity.kt

Replace MainActivity.kt with the complete example below. If you use another package or generated theme name, adjust those declarations and imports.

File: app/src/main/java/org/kodejava/tasknotes/MainActivity.kt

package org.kodejava.tasknotes

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import org.kodejava.tasknotes.data.sampleTasks
import org.kodejava.tasknotes.model.Task
import org.kodejava.tasknotes.ui.theme.TaskNotesTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        setContent {
            TaskNotesTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    TaskNotesScreen(
                        tasks = sampleTasks(),
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
    }
}

@Composable
private fun TaskNotesScreen(
    tasks: List<Task>,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "Task Notes",
            style = MaterialTheme.typography.headlineMedium,
            modifier = Modifier.padding(
                start = 24.dp,
                top = 24.dp,
                end = 24.dp
            )
        )
        Text(
            text = "Tasks: ${tasks.size}",
            style = MaterialTheme.typography.bodyMedium,
            modifier = Modifier.padding(horizontal = 24.dp)
        )

        if (tasks.isEmpty()) {
            Text(
                text = "No tasks yet.",
                modifier = Modifier.padding(24.dp)
            )
        } else {
            LazyColumn(
                modifier = Modifier.fillMaxWidth().weight(1f),
                contentPadding = PaddingValues(
                    horizontal = 24.dp,
                    vertical = 16.dp
                ),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                items(
                    items = tasks,
                    key = { task -> task.id }
                ) { task ->
                    TaskRow(task = task)
                }
            }
        }
    }
}

@Composable
private fun TaskRow(
    task: Task,
    modifier: Modifier = Modifier
) {
    Card(modifier = modifier.fillMaxWidth()) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            Text(
                text = task.title,
                style = MaterialTheme.typography.titleMedium
            )
            Text(
                text = if (task.isCompleted) "Completed" else "Not completed",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun TaskNotesScreenPreview() {
    TaskNotesTheme {
        TaskNotesScreen(tasks = sampleTasks())
    }
}

@Preview(showBackground = true)
@Composable
private fun EmptyTaskNotesScreenPreview() {
    TaskNotesTheme {
        TaskNotesScreen(tasks = emptyList())
    }
}

weight(1f) is available here through the surrounding Column scope. You do not need to add a separate weight import for this example.

3. Read the list code

The screen now accepts tasks: List<Task> as an argument. Its caller supplies sample data, while the screen describes how to display it. The same screen can therefore show the original samples, an empty list, or a larger collection without changing its implementation.

Inside LazyColumn, items() describes the repeated content:

items(
    items = tasks,
    key = { task -> task.id }
) { task ->
    TaskRow(task = task)
}

The items argument is the collection. The final lambda receives one task and describes its row. Import androidx.compose.foundation.lazy.items to use the collection overload.

Each key identifies an item across list changes. Our model’s distinct Long IDs remain suitable even when titles change or tasks move. Do not use the title as a key: two tasks can have the same title. A key must remain stable for that task and be unique within the list.

Keys do not save task data to disk or make a read-only list interactive. We will introduce observable state in the next article.

4. Understand the row and spacing

TaskRow() receives one Task and displays its title and status inside a Material 3 Card. The status uses words, so the user does not have to interpret a color to know whether a task is completed.

The row has no click handler or checkbox yet. Completion still comes from the values in SampleTasks.kt.

The layout uses several kinds of spacing:

Code Purpose
Modifier.padding(innerPadding) Keeps screen content clear of system bars through the existing Scaffold
weight(1f) Gives the list the remaining height below the header
contentPadding Adds space before, after, and beside the scrolling rows
Arrangement.spacedBy(12.dp) Adds space between task cards
Modifier.padding(16.dp) Adds space inside each card

Do not wrap this screen in a vertically scrolling Column. The list already scrolls, and it needs a bounded height. Here, the activity supplies the screen bounds and weight(1f) allocates the remaining space to the list.

5. Check the screen

Run the app on your emulator or phone. It should show Task Notes, Tasks: 3, and these cards:

Title Status
Learn Kotlin basics Not completed
Create the Task model Completed
Build the task list Not completed

All three cards may fit without scrolling. To check scrolling, temporarily replace tasks = sampleTasks() in MainActivity.onCreate() with:

tasks = List(50) { index ->
    Task(
        id = index.toLong() + 1L,
        title = "Practice task ${index + 1}",
        isCompleted = index % 3 == 0
    )
},

Keep the following modifier argument. Kotlin’s List(50) creates fifty elements using indexes from zero to forty-nine. Each generated task receives a different ID. The % operator returns the remainder, so indexes divisible by three produce completed tasks.

Run again, scroll to Practice task 50, and confirm that the header stays above the scrolling list. Restore tasks = sampleTasks() afterward.

To check the empty state, temporarily pass emptyList() instead. The count should become zero and the screen should show No tasks yet. Restore the original samples when finished.

The two preview functions also let you inspect populated and empty screens. This article’s Android build and device behavior have not been executed in an Android SDK environment; the checks above are steps to perform in your project.

Troubleshooting

  • If items expects an integer instead of your list, check the androidx.compose.foundation.lazy.items import.
  • If Compose reports duplicate keys, check that every task has a distinct ID. Repeating the same sample list without changing IDs creates duplicates.
  • If scrolling fails with an infinite-height constraint error, remove an outer vertical scroll container and keep the bounded layout shown above.
  • If your generated theme has another name, use that name in both the activity and previews.

Practice

  1. Add a fourth sample task with ID 4L and verify the count and new card.
  2. Give one task a longer title. Check that it wraps without hiding the status.
  3. Change the card spacing from 12.dp to 20.dp and compare the result.

Restore the original three samples before continuing.

Gradle dependencies and compatibility

No additional Gradle dependencies are required when continuing from articles 1 and 2. The example uses the existing Compose Foundation, Material 3, and preview dependencies.

Keep the plugin versions, Compose BOM, and version catalog generated for your working project. This lesson does not require a dependency upgrade. For configuration details, refer to the official Compose setup guide.

Unlike a Maven Java project, this Android project manages its dependencies through Gradle. There is no Maven dependency block to add for this article.

References

Next in the series

In article 4, How Do I Update Task Completion with State in Jetpack Compose?, you will add a checkbox and update a task’s completion status using observable state and copy().

How Do I Use Prompt Templates in Spring AI?

In Part 1, you built a Java assistant with POST /api/ask. Its instructions were the same for every reader. In this example, you will add a level field so a beginner receives a simpler explanation while an advanced reader receives more technical detail.

A prompt template is text with named placeholders. Spring AI fills those placeholders before sending the messages to the model. This is useful when the structure stays the same but some instructions change between requests.

Set up the project

Continue with the package org.kodejava.springai and the endpoint from Part 1. Use JDK 25 and Maven 3.9 or later. This article keeps Spring Boot 4.1.2 and Spring AI 2.0.2.

Use the complete POM at the end of this article. It uses spring-boot-starter-webmvc for the Spring Boot 4 servlet application and imports spring-ai-bom to manage the Spring AI dependencies.

Configure the model

Create or replace src/main/resources/application.properties:

server.address=127.0.0.1
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.chat.model=gpt-4o-mini

Use an OpenAI API key with access to the selected model. Set it in the environment of the terminal running Maven. Never put a real key in this file, the POM, a request body, or a Git commit. If your account cannot use this model, select an available chat model through the same property.

The chat.model property selects the OpenAI chat model in Spring AI 2.0, matching the configuration in Part 1.

Keep the application entry point

File: src/main/java/org/kodejava/springai/JavaAssistantApplication.java

package org.kodejava.springai;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JavaAssistantApplication {
    public static void main(String[] args) {
        SpringApplication.run(JavaAssistantApplication.class, args);
    }
}

Add a skill-level prompt template

Replace src/main/java/org/kodejava/springai/JavaAssistantController.java with:

package org.kodejava.springai;

import java.util.Locale;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@RestController
public class JavaAssistantController {
    private static final String SYSTEM_TEMPLATE = """
            You are a Java tutor teaching Java 25 in plain English.
            The reader's skill level is {level}.
            Follow these teaching instructions: {guidance}
            Include one short Java example when useful.
            Answer the Java question in the user message.
            """;

    private final ChatClient chatClient;

    public JavaAssistantController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @PostMapping("/api/ask")
    public AskResponse ask(@RequestBody AskRequest request) {
        if (request.question() == null || request.question().isBlank()) {
            throw new ResponseStatusException(
                    HttpStatus.BAD_REQUEST, "Question must not be blank");
        }
        String level = request.level() == null
                ? "beginner"
                : request.level().strip().toLowerCase(Locale.ROOT);
        String guidance = switch (level) {
            case "beginner" ->
                    "Define unfamiliar terms and use a small concrete example.";
            case "intermediate" ->
                    "Assume knowledge of classes and collections; explain tradeoffs.";
            case "advanced" ->
                    "Discuss relevant contracts, edge cases, and design implications.";
            default -> throw new ResponseStatusException(
                    HttpStatus.BAD_REQUEST,
                    "Level must be beginner, intermediate, or advanced");
        };

        String answer = chatClient.prompt()
                .system(system -> system.text(SYSTEM_TEMPLATE)
                        .param("level", level)
                        .param("guidance", guidance))
                .user(request.question())
                .call()
                .content();
        return new AskResponse(answer);
    }

    public record AskRequest(String question, String level) {}

    public record AskResponse(String answer) {}
}

{level} and {guidance} are placeholders. The param() calls supply their values. The lambda passed to system() configures one system message; it does not make a separate model call. Spring AI’s ChatClient uses prompt templating internally, so you do not need to create a separate PromptTemplate object here.

The question remains a separate user message. Send it through .user(request.question()) as ordinary text: do not concatenate it into the system template. This also makes questions containing Java braces easier to handle without treating them as template source.

The level is validated before the model call. Omitting it or sending null selects beginner, preserving the original one-field request. An empty level is rejected. Locale.ROOT makes case normalization independent of the machine’s locale.

The application chooses the teaching instructions from a fixed set. A caller cannot supply arbitrary guidance. Prompt instructions still do not guarantee accuracy or prevent every attempt to redirect a model; review generated Java code before using it.

Run the application

From the folder containing pom.xml, check the tools:

java -version
mvn -version

Both should report Java 25. Build with mvn clean package.

In Bash on Linux or macOS, read the key without adding it to shell history:

read -r -s -p 'OpenAI API key: ' OPENAI_API_KEY
printf '\n'
export OPENAI_API_KEY
mvn spring-boot:run

In PowerShell 7.2 or later:

$env:OPENAI_API_KEY = Read-Host 'OpenAI API key' -MaskInput
mvn spring-boot:run

The key is still held in the process environment; masking prevents it from being displayed while entering it. Stop the app with Ctrl+C. Clear the value afterward with unset OPENAI_API_KEY in Bash or Remove-Item Env:OPENAI_API_KEY in PowerShell.

Compare explanations

Open a second terminal. In a Unix shell:

curl -i http://127.0.0.1:8080/api/ask \
  -H 'Content-Type: application/json' \
  -d '{"question":"How does a HashSet detect duplicates?","level":"beginner"}'

In PowerShell:

$body = @{
    question = 'How does a HashSet detect duplicates?'
    level = 'beginner'
} | ConvertTo-Json
Invoke-RestMethod -Uri 'http://127.0.0.1:8080/api/ask' `
    -Method Post -ContentType 'application/json' -Body $body

A possible HTTP 200 body is:

{"answer":"A HashSet stores unique elements. It uses hashCode() to help find where an element belongs, then equals() to compare elements when needed. Adding the same String twice leaves one copy."}

Repeat with advanced. You might receive a discussion of the equals() / hashCode() contract, collisions, and mutable keys. The response still has one answer field; wording and example code vary between calls. The level guides the model rather than enforcing a measurable difficulty score.

Check these cases with either client:

Request body Expected result
{"question":"What is a record?"} HTTP 200, beginner guidance
{"question":"What is a record?","level":"ADVANCED"} HTTP 200, advanced guidance
{"question":"What is a record?","level":"expert"} HTTP 400, no model call
{"question":" ","level":"beginner"} HTTP 400, no model call

Do not rely on an exact error JSON body: Spring Boot error settings affect which details are exposed. Invalid JSON is also rejected by Spring MVC before this method executes.

A 401 from the provider usually requires checking the API key. For a model-access error, check the model setting and your account permissions. A 429 requires checking provider rate limits or billing. Avoid printing your key while troubleshooting.

Try it yourself

Ask the same question at all three levels. Compare whether unfamiliar terms are defined and whether the advanced answer adds useful edge cases. Then change the beginner guidance to request an analogy and repeat. Keep expectations about HTTP status and JSON shape separate from expectations about generated wording.

Part 3 will cover How Do I Map Structured AI Output to Java Records? Later articles will introduce Ollama, document question answering with PostgreSQL vector search, and Java tool calling before moving to evaluation and operational concerns.

References

Maven artifacts

File: pom.xml. Maven Central is sufficient; no milestone repository is needed. The Boot parent manages the web starter and build plugin, and the AI BOM manages the OpenAI starter.

<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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.2</version>
        <relativePath/>
    </parent>
    <groupId>org.kodejava</groupId>
    <artifactId>spring-ai-java-assistant</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>25</java.version>
        <spring-ai.version>2.0.2</spring-ai.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-model-openai</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>