Run a Java App in the Browser (SwingSet3)
Porting a Swing application to the web
In this tutorial, weβll run the SwingSet3 application in the browser.
View demoPrerequisites
- Download the template project and unzip it
- Node.js
(>= 18)
The starting point of this example is an empty HTML page, the SwingSet3 jar, and its dependencies:
.βββ index.htmlβββ SwingSet3.jarβββ lib βββ AnimatedTransitions.jar βββ AppFramework.jar βββ Filters.jar βββ MultipleGradientPaint.jar βββ TimingFramework.jar βββ javaws.jar βββ swing-layout-1.0.jar βββ swing-worker.jar βββ swingx.jar1. 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.
npx viteVisit 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.
Alternatively you can also use the http-server utility.
npx http-server -p 8080Open a browser tab pointing to your localhost such as http://127.0.0.1:8080/.
2. Add CheerpJ to the document
Letβs add CheerpJ to the page by adding this script tag to the <head>:
<script src="https://cjrtnc.leaningtech.com/4.2/loader.js"></script>3. Initialise CheerpJ and run the jar
Add the following script tag to the <body>:
<script type="module"> await cheerpjInit(); cheerpjCreateDisplay(800, 600); await cheerpjRunJar("/app/SwingSet3.jar");</script>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 <body>:
<div id="container"></div>NoteMake sure you add the container element before the script which calls cheerpjCreateDisplay.
And then add some CSS:
<style> html, body { margin: 0; }
#container { width: 100vw; height: 100svh; }</style>Finally, update the script to use the container element:
<script type="module"> await cheerpjInit(); cheerpjCreateDisplay(-1, -1, document.getElementById("container")); await cheerpjRunJar("/app/SwingSet3.jar");</script>Passing -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.