How do I update task completion with state in Jetpack Compose?

Android Programming Essentials

In article 3, Task Notes displayed three sample tasks in a scrolling list. Each row showed whether a task was complete. This time, you will add a checkbox to each row and update the completion count as you check and uncheck tasks.

By the end, you will have a screen that reads observable state, sends user events through callbacks, and updates one task without changing its ID.

1. Open the Task Notes project

Continue from article 3. Keep the existing model/Task.kt and data/SampleTasks.kt. The model already supplies a Long ID, a title, and an isCompleted flag. The sample list starts with three tasks, one of which is complete.

If you chose a different package name, keep your package and use the imports for your existing model, sample data, and theme.

2. Replace MainActivity.kt

Open app/src/main/java/org/kodejava/tasknotes/MainActivity.kt and replace its contents with the following code.

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.Row
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.Checkbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
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 ->
                    TaskNotesRoute(
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
    }
}

@Composable
private fun TaskNotesRoute(modifier: Modifier = Modifier) {
    var tasks by remember { mutableStateOf(sampleTasks()) }

    TaskNotesScreen(
        tasks = tasks,
        onTaskCheckedChange = { taskId, isCompleted ->
            tasks = tasks.map { task ->
                if (task.id == taskId) task.copy(isCompleted = isCompleted)
                else task
            }
        },
        modifier = modifier
    )
}

@Composable
private fun TaskNotesScreen(
    tasks: List<Task>,
    onTaskCheckedChange: (Long, Boolean) -> Unit,
    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} · Completed: ${tasks.count { it.isCompleted }}",
            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,
                        onCheckedChange = { checked ->
                            onTaskCheckedChange(task.id, checked)
                        }
                    )
                }
            }
        }
    }
}

@Composable
private fun TaskRow(
    task: Task,
    onCheckedChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    Card(modifier = modifier.fillMaxWidth()) {
        Row(
            modifier = Modifier.fillMaxWidth().padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(
                modifier = Modifier.weight(1f),
                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
                )
            }
            Checkbox(
                checked = task.isCompleted,
                onCheckedChange = onCheckedChange,
                modifier = Modifier.semantics { contentDescription = task.title }
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun TaskNotesScreenPreview() {
    TaskNotesTheme {
        TaskNotesScreen(tasks = sampleTasks(), onTaskCheckedChange = { _, _ -> })
    }
}

@Preview(showBackground = true)
@Composable
private fun EmptyTaskNotesScreenPreview() {
    TaskNotesTheme {
        TaskNotesScreen(tasks = emptyList(), onTaskCheckedChange = { _, _ -> })
    }
}

3. Give the screen one source of state

TaskNotesRoute owns the current list. The first time Compose calls it, remember runs its initializer and stores the state object. On recomposition, Compose reuses that object while the route remains in the composition. mutableStateOf makes changes observable, and the Kotlin by delegate lets you read or assign its value using tasks.

TaskNotesScreen receives the list as a parameter. Both the completion count and the checkboxes read from that same list. The count is computed from the current data, so checking or unchecking a task requires only one state change.

This example keeps edits in memory for the current composition. Rotating a device typically recreates this activity and loads the sample values again. Persistent task storage comes later in the series. See State and Jetpack Compose.

4. Follow a checkbox event

  1. The checkbox displays the value of task.isCompleted.
  2. When the user taps it, onCheckedChange supplies the requested Boolean.
  3. The list passes the task ID and Boolean to the route through onTaskCheckedChange.
  4. The route calls map to build a new list. For the task with that ID, copy(isCompleted = isCompleted) creates a task with the updated flag and preserves the other fields.
  5. The assignment to tasks updates the observed state. Compose can then recompose the UI that read it to display the new checkbox state and count.

Compose calls this pattern state hoisting when a caller owns the state and passes values and callbacks to its children. Here, the row gets its value from the screen, and the event travels back to the route that owns the list. The lazy list continues to use each task’s ID as a stable key. See Compose UI architecture and Checkbox.

5. Verify the result

Run the app in Android Studio on an emulator or phone. Check the following actions in order.

Action Expected result
Launch Task Notes Three rows appear. Only Create the Task model is checked, and the header shows Completed: 1.
Check Learn Kotlin basics Its status becomes Completed, and the header shows Completed: 2.
Uncheck Create the Task model Its status becomes Not completed, and the header shows Completed: 1.
Uncheck Learn Kotlin basics All rows are unchecked, and the header shows Completed: 0. The total remains three.
Relaunch after stopping the app The original sample data appears again.

Use the populated and empty previews to inspect layout, then run the app to verify state changes. The previews pass callbacks with empty bodies. The example was reviewed against the preceding drafts and Android documentation. It still needs a build and emulator check in Android Studio.

If the box changes but the header fails to follow, check that both values come from the list passed to TaskNotesScreen. If neither changes, check that the row forwards the requested Boolean and that the route assigns the result of map back to tasks.

Practice

  1. Display the number of remaining tasks next to the completed count. Derive it from tasks, then verify it updates after every tap.
  2. Give two sample tasks the same title while keeping their IDs distinct. Toggle one and verify that only the row you touched changes. Restore the sample titles afterward.

Gradle dependencies

This example uses the Compose Runtime, Foundation, and Material 3 already available in the Task Notes project. Keep the project’s existing Gradle configuration and Compose BOM. See Set up Jetpack Compose for the official setup instructions.

Next in the series

In article 5, you will add a form for entering a task title, check that it contains text, and put the new task in the list.

How do I map structured AI output to Java records?

Spring AI Banner

In Part 2, our Java assistant used prompt templates to match the reader’s skill level. Now we will add POST /api/explain and return a summary, key points, and Java code as separate fields. Keep the existing /api/ask controller alongside this new endpoint.

Set up the project

Use JDK 25 and Maven 3.9 or later. This article retains Spring Boot 4.1.2 and Spring AI 2.0.2 from Parts 1 and 2. Spring’s compatibility guide supports Boot 4.1.x with AI 2.0.x. Use the complete POM at the end.

Configure the model

File: 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. Never commit credentials or include them in requests or logs. API usage has separate billing from a ChatGPT subscription.

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);
    }
}

Define a response record

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

package org.kodejava.springai;

import java.util.List;

public record JavaExplanation(String summary, List<String> keyPoints,
                              String exampleCode) {
}

The record describes the expected data. Its generated accessors include summary() and keyPoints(). A UI can display each field separately. A record does not validate its contents or make a contained list immutable.

Add the endpoint

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

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 JavaExplanationController {
    private final ChatClient client;

    public JavaExplanationController(ChatClient.Builder builder) {
        this.client = builder.build();
    }

    @PostMapping("/api/explain")
    public JavaExplanation explain(@RequestBody ExplainRequest 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 with a concrete example.";
            case "intermediate" -> "Assume knowledge of classes; explain tradeoffs.";
            case "advanced" -> "Discuss contracts, edge cases, and design implications.";
            default -> throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Level must be beginner, intermediate, or advanced");
        };
        JavaExplanation result = client.prompt()
                .system(s -> s.text("""
                        You are a Java 25 tutor writing plain English.
                        Reader level: {level}. Teaching guidance: {guidance}
                        Provide a short summary, three useful key points,
                        and one small Java example. In exampleCode, use
                        Java source without Markdown fences.
                        Answer the question in the user message.
                        """).param("level", level).param("guidance", guidance))
                .user(request.question())
                .call()
                .entity(JavaExplanation.class);
        if (result == null || result.summary() == null || result.summary().isBlank()
                || result.keyPoints() == null || result.keyPoints().size() != 3
                || result.keyPoints().stream().anyMatch(p -> p == null || p.isBlank())
                || result.exampleCode() == null || result.exampleCode().isBlank()) {
            throw new ResponseStatusException(HttpStatus.BAD_GATEWAY,
                    "Model returned an incomplete explanation");
        }
        return result;
    }

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

The skill-level template follows Part 2. Omitting level selects beginner guidance; an empty or unknown value returns HTTP 400 before a model call. The question stays in a separate user message.

The key change is .call().entity(JavaExplanation.class) instead of .call().content(). Spring AI derives a JSON schema from the record, requests structured output, and converts the model reply into the record. Spring MVC then serializes that Java object into HTTP JSON. No manual string splitting is needed.

The application check enforces useful content and exactly three points. Declaring List<String> alone does not require three elements. A parsed but incomplete answer returns HTTP 502. A conversion exception happens before this check and normally produces HTTP 500 in this minimal application. Provider failures also propagate; a later article will add a consistent exception handler.

Understand the limits

Basic entity() is best effort. A model can produce output that cannot be converted. Successful parsing does not prove factual correctness or that generated Java compiles. Review code before using it and never execute it automatically.

Spring AI also provides provider-native structured output and schema validation with self-correction. Those features improve structural reliability but do not establish factual accuracy. Retries can add latency and cost. We will introduce reliability policies separately. Typed conversion requires the complete response, so this example uses call(), not stream().

Build and run

Check java -version and mvn -version; Maven should use JDK 25. Build from the project directory:

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

Run Maven in the same terminal. Masking hides input; the credential still exists in the process environment. Stop with Ctrl+C, then clear it using unset OPENAI_API_KEY in Bash or Remove-Item Env:OPENAI_API_KEY in PowerShell.

Send a request

From another Unix terminal:

curl -i http://127.0.0.1:8080/api/explain -H 'Content-Type: application/json' -d '{"question":"How do Java records reduce boilerplate?","level":"beginner"}'

In PowerShell:

$body = @{ question = 'How do Java records reduce boilerplate?'; level = 'beginner' } | ConvertTo-Json
Invoke-RestMethod -Uri 'http://127.0.0.1:8080/api/explain' -Method Post -ContentType 'application/json' -Body $body | ConvertTo-Json -Depth 5

An illustrative HTTP 200 response:

{
  "summary": "Records provide a concise way to declare data classes.",
  "keyPoints": [
    "The header declares the components.",
    "Java generates accessors, equals, hashCode, and toString.",
    "Component fields are final, but referenced objects can be mutable."
  ],
  "exampleCode": "record Person(String name, int age) {}"
}

Wording and code vary. The response has fields directly rather than an answer string containing JSON. Escaped line breaks inside a JSON code string are normal.

Request or condition Expected behavior
Valid question without level Beginner guidance; HTTP 200 if conversion and checks succeed
Level ADVANCED Advanced guidance after normalization
Blank question HTTP 400; no model call
Level expert HTTP 400; no model call
Parsed answer missing required content HTTP 502
Unconvertible model output Server error; no successful record response

Error body details depend on Spring Boot configuration. For provider 401 errors, check the running process’s key. For 429, inspect billing and rate limits. Do not print the credential while troubleshooting.

Try it yourself

Compare the same question at all three levels while checking that the field names stay consistent. Next add an exercise component, update the prompt, and validate that field. Decide which rules need explicit application checks.

Part 4 will introduce Ollama. Later articles will build document question answering with PostgreSQL vector search and Java tool calling, then progress to evaluation and operational concerns.

References

Maven artifacts

File: pom.xml. Maven Central is sufficient. The Boot parent manages the web starter and plugin; 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>

How do I animate a particle hourglass in Java Swing?

You can create an hourglass animation by assigning each particle a starting position, a launch time, and a destination. Moving the particles through a shared point at the neck gives the impression of sand passing between two chambers.

Particle Hourglass
Particle Hourglass

This SwingLoops example uses 650 golden particles, smoothstep easing, and a Java 2D clipping region. It is a stylized animation rather than a simulation of granular material.

Source code

Save this code as ParticleHourglass.java:

import java.awt.*;
import java.awt.geom.*;
import java.util.Random;
import javax.swing.*;

public class ParticleHourglass extends JPanel {
    private static final int W = 450, H = 800, COUNT = 650;
    private static final double CYCLE = 12;
    private final double[] x = new double[COUNT], y = new double[COUNT];
    private final Timer timer = new Timer(16, _ -> repaint());
    private long start;

    public ParticleHourglass() {
        setPreferredSize(new Dimension(W, H));
        setBackground(new Color(8, 15, 27));
        Random random = new Random(42);
        for (int i = 0; i < COUNT; i++) {
            // Uniform sampling in the upper triangular chamber.
            double depth = Math.sqrt(random.nextDouble());
            x[i] = (random.nextDouble() * 2 - 1) * 130 * depth;
            y[i] = -210 * depth;
        }
    }

    @Override public void addNotify() {
        super.addNotify();
        start = System.nanoTime();
        timer.start();
    }

    @Override public void removeNotify() {
        timer.stop();
        super.removeNotify();
    }

    private static double clamp(double u) {
        return Math.max(0, Math.min(1, u));
    }

    private static double ease(double u) {
        return u * u * (3 - 2 * u);
    }

    @Override protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        Graphics2D g = (Graphics2D) graphics.create();
        try {
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            double scale = Math.min(getWidth() / (double) W,
                                    getHeight() / (double) H);
            g.translate(getWidth() / 2.0, getHeight() / 2.0);
            g.scale(scale, scale);

            double t = ((System.nanoTime() - start) / 1e9) % CYCLE;
            // Fade before resetting the particle positions.
            float alpha = (float) Math.min(clamp(t / .3), clamp(12 - t));
            g.setComposite(AlphaComposite.SrcOver.derive(alpha));

            Path2D chamber = new Path2D.Double();
            chamber.moveTo(-140, -220);
            chamber.lineTo(140, -220);
            chamber.lineTo(0, 0);
            chamber.closePath();
            chamber.moveTo(0, 0);
            chamber.lineTo(140, 220);
            chamber.lineTo(-140, 220);
            chamber.closePath();

            Graphics2D sand = (Graphics2D) g.create();
            try {
                sand.clip(chamber);
                for (int i = 0; i < COUNT; i++) {
                    double launch = .6 + 7.5 * i / (COUNT - 1.0);
                    double u = clamp((t - launch) / 1.15);
                    double px, py;
                    if (u < .5) {
                        double blend = ease(u * 2);
                        px = x[i] * (1 - blend);
                        py = y[i] * (1 - blend);
                    } else {
                        double blend = ease((u - .5) * 2);
                        px = -x[i] * blend;
                        py = -y[i] * blend;
                    }
                    sand.setColor(new Color(248,
                            171 + i % 60, 66 + i % 45));
                    sand.fill(new Ellipse2D.Double(px - 1.3, py - 1.3, 2.6, 2.6));
                }
            } finally {
                sand.dispose();
            }

            g.setColor(new Color(118, 206, 225, 180));
            g.setStroke(new BasicStroke(2f));
            g.draw(chamber);
            g.setColor(new Color(203, 225, 237));
            g.fillRoundRect(-157, -233, 314, 12, 8, 8);
            g.fillRoundRect(-157, 221, 314, 12, 8, 8);
        } finally {
            g.dispose();
        }
    }

    static void main() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("SwingLoops - Particle Hourglass");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new ParticleHourglass());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Run the example

You need a JDK 25 and a desktop environment that supports Swing. Open a terminal in the source directory:

javac ParticleHourglass.java
java ParticleHourglass

Fill a triangular chamber

Each particle starts inside the upper triangle. The distance from the neck is sampled using a square root:

double depth = Math.sqrt(random.nextDouble());
x[i] = (random.nextDouble() * 2 - 1) * 130 * depth;
y[i] = -210 * depth;

The available width grows with depth. A uniform depth distribution would crowd the narrow region near the neck relative to its area. Taking the square root gives greater weight to wider slices, producing a uniform distribution over the interior of the sampling triangle.

A fixed random seed makes the arrangement repeatable between runs.

Give each particle a launch time

Particles do not start together. Their launch times are distributed over 7.5 seconds:

double launch = .6 + 7.5 * i / (COUNT - 1.0);
double u = clamp((t - launch) / 1.15);

The first particle begins at 0.6 seconds. The last begins at 8.1 seconds and finishes at 9.25 seconds. Before launch, its progress is clamped to zero. After arrival, it is clamped to one.

Launch order follows particle index, not physical height. Particles can cross one another and do not collide.

Route each particle through the neck

The journey has two stages. During the first half, interpolation brings the particle from its initial position to the origin. During the second half, it moves from the origin to the mirrored destination (-x, -y).

For each stage, smoothstep transforms progress:

return u * u * (3 - 2 * u);

Its slope is zero at both endpoints. That creates gentle starts and stops, including a brief slowing at the neck. This controlled motion does not model gravitational acceleration.

Mirroring the initial coordinates places every destination inside the lower triangle, so all particles have valid endpoints without a packing algorithm.

Keep particles inside the glass

The two triangular chambers form a Path2D. A copied graphics context uses that path as its clipping region:

sand.clip(chamber);

Clipping prevents particle circles from protruding outside the chamber boundary. At the exact neck, the chamber has zero width, so particles may be partially or fully clipped while crossing. The glass outline is drawn afterward using the unclipped parent context.

Repeat the sequence

The sequence lasts 12 seconds. It fades in over the first 0.3 seconds and fades out from 11 to 12 seconds. Particle positions reset while the drawing is transparent.

A Swing timer requests repaints approximately every 16 milliseconds. Motion is based on elapsed time from System.nanoTime(), so a delayed repaint does not alter the planned arrival times. The interface, painting, and timer callbacks run on Swing’s event-dispatch thread.

Customize the animation

Try changing COUNT from 650 to 400 for a sparser result. Increasing the launch-time spread produces a slower transfer, but keep the last arrival before the fade starts at 11 seconds.

You can also adjust particle size and colors. For more realistic sand behavior, a future implementation would need collision handling and a settling model; this example deliberately uses predefined paths.

The complete source code above is free to copy and run. Explore the SwingLoops repository for more Java animation examples.

How do I create a drop-down list using JComboBox in Java Swing?

Use JComboBox to let the user choose one item from a drop-down list. In this example, selecting a programming language updates a label below the list.

Source code

Save the following code as ComboBoxExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

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

    private void showWindow() {
        String[] languages = {"Java", "Python", "Kotlin"};
        JComboBox<String> languageBox = new JComboBox<>(languages);

        JLabel prompt = new JLabel("Choose a language:");
        prompt.setLabelFor(languageBox);

        JLabel selection = new JLabel(
                "Selected: " + languageBox.getSelectedItem(),
                SwingConstants.CENTER);

        languageBox.addActionListener(event ->
                selection.setText(
                        "Selected: " + languageBox.getSelectedItem()));

        JPanel controls = new JPanel();
        controls.add(prompt);
        controls.add(languageBox);

        JPanel content = new JPanel(new BorderLayout(0, 10));
        content.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
        content.add(controls, BorderLayout.PAGE_START);
        content.add(selection, BorderLayout.CENTER);

        JFrame frame = new JFrame("Language Picker");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration of the Language Picker window with Python selected and the label Selected: Python below it

Explanation

new JComboBox<>(languages) creates a drop-down list from the array. The first item, Java, is selected when the window opens. The list is non-editable by default, so the user chooses from the supplied options.

Use getSelectedItem() to read the current selection. It returns an Object, which you can concatenate directly with a label such as "Selected: ". If there is no selection, it returns null. This example always starts with a selection and offers no way to clear it.

addActionListener() registers code that Swing calls when the user makes a selection. The listener reads the current item and updates the existing label with setText().

Run the example

javac ComboBoxExample.java
java ComboBoxExample

The window opens with Selected: Java. Choose Python from the drop-down list, and the label changes to Selected: Python.

How do I arrange a form using GridBagLayout in Java Swing?

Use GridBagLayout to arrange labels and fields in rows and columns. You can give each component its own position and decide how it should resize.

In this example, the labels stay on the left while the text fields on the right grow wider when you resize the window.

Source code

Save the following code as GridBagLayoutExample.java:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

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

    private void showWindow() {
        JPanel form = new JPanel(new GridBagLayout());

        addRow(form, 0, "Name:");
        addRow(form, 1, "Email:");

        JFrame frame = new JFrame("Contact Form");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(form);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void addRow(JPanel form, int row, String labelText) {
        JLabel label = new JLabel(labelText);
        JTextField field = new JTextField(20);
        label.setLabelFor(field);

        GridBagConstraints labelConstraints = new GridBagConstraints();
        labelConstraints.gridx = 0;
        labelConstraints.gridy = row;
        labelConstraints.anchor = GridBagConstraints.LINE_START;
        labelConstraints.insets = new Insets(6, 8, 6, 8);
        form.add(label, labelConstraints);

        GridBagConstraints fieldConstraints = new GridBagConstraints();
        fieldConstraints.gridx = 1;
        fieldConstraints.gridy = row;
        fieldConstraints.weightx = 1.0;
        fieldConstraints.fill = GridBagConstraints.HORIZONTAL;
        fieldConstraints.insets = new Insets(6, 8, 6, 8);
        form.add(field, fieldConstraints);
    }
}

What the form looks like

Illustration of the contact form with Name and Email labels on the left and fields that stretch horizontally on the right

Explanation

GridBagLayout places components in an invisible grid. Each call to form.add() passes a component and a GridBagConstraints object that tells Swing how to place it.

Setting What it does in this example
gridx Selects the column: 0 for labels and 1 for fields
gridy Selects the row: 0 for Name and 1 for Email
anchor Aligns the label at the start of its cell
insets Adds space outside each component, in top, left, bottom, right order
weightx Gives the field column the extra horizontal space
fill Lets each field stretch horizontally to use that space

weightx and fill do different jobs. weightx determines which column receives extra width. fill determines whether a component grows to use the width of its cell. Without HORIZONTAL fill, the field could stay at its preferred width even when its column grows.

frame.pack() sizes the window to fit the form at its preferred size. The whole window is created on Swing’s event dispatch thread using invokeLater().

Run the example

javac GridBagLayoutExample.java
java GridBagLayoutExample

The Contact Form window opens with two rows. Drag the right edge outward to see both text fields widen while the labels stay aligned.