Skip to content

3. Call Java from the page

fakeivchenko edited this page Sep 28, 2026 · 1 revision

A binding makes a Java function callable from JavaScript. In this step, the Save button hands the note to Java, which stores it and answers with a status message.

  1. In Main.java, bind a function named saveNote:

    package com.example.notes;
    
    import dev.ivchenko.lwjwae.Application;
    import dev.ivchenko.lwjwae.Window;
    import dev.ivchenko.lwjwae.WindowParameters;
    import java.util.List;
    import java.util.concurrent.CopyOnWriteArrayList;
    
    public class Main {
      private static final List<String> NOTES = new CopyOnWriteArrayList<>();
    
      public static void main(String[] args) {
        Application.launch(WindowParameters.of("Notes", "app/index.html"), Main::setUp);
      }
    
      static void setUp(Window window) {
        window.bind(
            "saveNote",
            note -> {
              NOTES.add(note);
              return "Saved " + NOTES.size() + (NOTES.size() == 1 ? " note" : " notes");
            });
      }
    }

    setUp runs before the page loads, so the page finds saveNote from its first line of script. The handler runs on a virtual thread of its own, so it can block, read files, or call a server without freezing the window.

  2. In src/main/resources/app/app.js, call the function when the user clicks Save:

    const note = document.querySelector("#note");
    const status = document.querySelector("#status");
    
    document.querySelector("#save").addEventListener("click", async () => {
      status.textContent = await window.saveNote(note.value);
      note.value = "";
    });

    Every binding is an async function on the page: it returns a promise that resolves to what the Java handler returns.

  3. In index.html, load the script at the end of body:

        <script src="app.js"></script>
      </body>
  4. Run the application, write a note, and click Save:

    The page shows "Saved 1 note" after the click


Previous: Open a window · Next: Send events from Java to the page

Clone this wiki locally