Porting a Swing application to the web
In this tutorial, we’ll run the SwingSet3 application in the browser.View demo
The starting point of this example is an empty HTML page, the SwingSet3 jar, and its dependencies:
1. Run a web server
To view the example, we need to host the files on a web server. Vite is a convenient tool for this, as it automatically reloads the page when the files change.
Visit the URL shown in the terminal and you should see a blank page. Leave Vite running in the background for the remainder of this tutorial.
2. Add CheerpJ to the document
Let’s add CheerpJ to the page by adding this script tag to the
3. Initialise CheerpJ and run the jar
Add the following script tag to the
This will initialise CheerpJ, create a 800x600 display, and run the SwingSet3 jar. We use
type="module" so that we can use top-level await.
What is /app/SwingSet3.jar?This is a virtual filesystem which represents the root of the web server.
Save the file and you should see SwingSet3 load and run in the browser. 🥳
4. Make the application take up the whole page
The application takes up a small portion of the page, but for many applications we want to take up the whole page.
To do this, we’ll add a new element to the
NoteMake sure you add the container element before the script which calls cheerpjCreateDisplay.
And then add some CSS:
Finally, update the script to use the container element:
-1 as the width and height tells CheerpJ to use the full size of the container element, and listen for resize events.
View the page again, and you should see the application take up the entire window. Also notice that resizing the window resizes the application.
View full source code on GitHub