3. Call Java from the page - fakeivchenko/lwjwae GitHub Wiki
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.
-
In
Main.java, bind a function namedsaveNote: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"); }); } }
setUpruns before the page loads, so the page findssaveNotefrom 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. -
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
asyncfunction on the page: it returns a promise that resolves to what the Java handler returns. -
In
index.html, load the script at the end ofbody:<script src="app.js"></script> </body>
-
Run the application, write a note, and click Save:

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