Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

HTML/CSS/JavaScript GUI in Java Swing Application

DZone's Guide to

HTML/CSS/JavaScript GUI in Java Swing Application

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

There are a log of desktop applications that integrate web browser control to display HTML content and communicate with web services and web applications directly from app: iTunes, Adobe Brackets, Evernote, Amazon Music, Steam Client, etc. If you develop similar type of a desktop application using Java technology, and you need to embed safe, fast, lightweight web browser control that supports all modern web technologies such as HTML5, CSS, JavaScript, Flash, etc., then JxBrowser is what you need.

The following code demonstrates how simple the process of embedding web browser component into your Java Swing/AWT/JavaFX desktop application:

Swing/AWT

01. importcom.teamdev.jxbrowser.chromium.Browser;
02. importcom.teamdev.jxbrowser.chromium.swing.BrowserView;
03.  
04. importjavax.swing.*;
05. importjava.awt.*;
06.  
07. publicclassBrowserSample {
08.    publicstaticvoidmain(String[] args) {
09.        Browser browser = newBrowser();
10.        BrowserView browserView = newBrowserView(browser);
11.  
12.        JFrame frame = newJFrame("JxBrowser");
13.        frame.add(browserView, BorderLayout.CENTER);
14.        frame.setSize(700, 500);
15.        frame.setVisible(true);
16.  
17.        browser.loadURL("http://www.google.com");
18.    }
19. }

JavaFX

01. importcom.teamdev.jxbrowser.chromium.Browser;
02. importcom.teamdev.jxbrowser.chromium.javafx.BrowserView;
03.  
04. importjavafx.application.Application;
05. importjavafx.scene.Scene;
06. importjavafx.scene.layout.StackPane;
07. importjavafx.stage.Stage;
08.  
09. publicclassJavaFXSample extendsApplication {
10.    @Override
11.    publicvoidstart(Stage primaryStage) {
12.        Browser browser = newBrowser();
13.        BrowserView browserView = newBrowserView(browser);
14.  
15.        StackPane pane = newStackPane();
16.        pane.getChildren().add(browserView);
17.        Scene scene = newScene(pane, 700, 500);
18.        primaryStage.setScene(scene);
19.        primaryStage.show();
20.  
21.        browser.loadURL("http://www.google.com");
22.    }
23.  
24.    publicstaticvoidmain(String[] args) {
25.        launch(args);
26.    }
27. }


Note: take a look at Quick Start Guide to get more information about how to add JxBrowser library into your Java project using your favorite IDE.

HTML+CSS+JavaScript as a GUI

With JxBrowser your Java desktop application GUI can be built with HTML+CSS+JavaScript. It means that you can actually use any modern HTML5 UI toolkit to build modern, user-friendly interface of your Java desktop application. You don’t need to hire Swing/AWT developers. GUI of your Java app can be built by HTML+CSS+JavaScript developers. It significantly reduces the cost of Java project development.

The following simple application demonstrates how to create New Account Dialog built with HTML+CSS+JavaScript into your Java Swing/AWT desktop application.

First we create HTML document with New Account dialog content. In the following document we use one of the most popular Bootstrap HTML UI framework to build dialog’s UI:

01. <!DOCTYPE html>
02. <html>
03. <head>
04.    <metacharset="utf-8"/>
05.    <title>Registration Form</title>
07.    <linkhref='http://fonts.googleapis.com/css?family=Roboto:300'rel='stylesheet'type='text/css'>
08.    <scriptsrc="http://code.jquery.com/jquery-1.11.1.min.js"></script>
10.    <style>
11.        body{
12.            font:12px/15px Roboto, "Helvetica Neue", Helvetica, sans-serif;
13.        }
14.        select,
15.        input,
16.        .btn {
17.            font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
18.        }
19.        #wrapper{
20.            margin:0 auto;
21.        }
22.        .main-form {
23.            width: 360px;
24.            min-height: 360px;
25.            background: #fff;
26.            border-radius: 60px;
27.            margin:0px auto 20px;
28.            padding: 20px;
29.        }
30.        .form-logo {
31.            font-size: 100px;
32.            color: #708090;
33.        }
34.    </style>
35. </head>
36. <body>
37. <script>
38. function newAccount() {
39.    var firstName = document.getElementById("firstname").value;
40.    var lastName = document.getElementById("lastname").value;
41.    var phone = document.getElementById("phone").value;
42.    var email = document.getElementById("email").value;
43.    // Call Java callback function and pass text fields values.
44.    onCreateAccount(firstName, lastName, phone, email);
45. }
46. </script>
47. <divid="wrapper">
48.    <divclass="main-form">
49.        <formaction="#"method="POST">
50.            <fieldset>
51.                <divclass="text-center">
52.                    <spanclass="form-logo glyphicon glyphicon-user"></span>
53.                </div>
54.                <divclass="form-body">
55.                    <h1class="form-title text-center">New Account</h1>
56.                    <divclass="form-group">
57.                        <inputclass="form-control"type="text"id="firstname"name="firstname"placeholder="First Name">
58.                    </div>
59.                    <divclass="form-group">
60.                        <inputclass="form-control"type="text"id="lastname"name="surname"placeholder="Last Name">
61.                    </div>
62.                    <divclass="form-group">
63.                        <inputclass="form-control"type="text"id="phone"name="phone"placeholder="Phone">
64.                    </div>
65.                    <divclass="form-group">
66.                        <inputclass="form-control"type="email"id="email"name="email"placeholder="Email">
67.                    </div>
68.                    <divclass="form-group text-center">
69.                        <buttonclass="btn btn-default btn-lg"type="button"onclick="newAccount();">New Account</button>
70.                    </div>
71.                </div>
72.            </fieldset>
73.        </form>
74.    </div>
75. </div>
76. </body>
77. </html>

This dialog has First Name, Last Name, Phone, Email text fields, and New Account button. In Java application we need to display a dialog with this HTML content, let the user to fill all text fields and click New Account button. In Java code we need to be notified when user clicks the button, read text fields values to create a new account in our application. The following Java example demonstrates how we can do it with JxBrowser:

001. importcom.teamdev.jxbrowser.chromium.Browser;
002. importcom.teamdev.jxbrowser.chromium.BrowserFunction;
003. importcom.teamdev.jxbrowser.chromium.JSValue;
004. importcom.teamdev.jxbrowser.chromium.swing.BrowserView;
005.  
006. importjavax.swing.*;
007. importjava.awt.*;
008. importjava.awt.event.ActionEvent;
009. importjava.awt.event.ActionListener;
010. importjava.awt.event.WindowAdapter;
011. importjava.awt.event.WindowEvent;
012. importjava.util.concurrent.atomic.AtomicReference;
013.  
014. publicclassHTMLUISample {
015.    publicstaticvoidmain(String[] args) {
016.        finalJFrame frame = newJFrame("HTMLUISample");
017.        finalJButton newAccountButton = newJButton("New Account...");
018.        newAccountButton.addActionListener(newActionListener() {
019.            @Override
020.            publicvoidactionPerformed(ActionEvent e) {
021.                Account account = createAccount(frame);
022.                // Displays created account's details
023.                JOptionPane.showMessageDialog(frame, "Created Account: "+ account);
024.            }
025.        });
026.  
027.        JPanel contentPane = newJPanel();
028.        contentPane.add(newAccountButton);
029.  
030.        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
031.        frame.add(contentPane, BorderLayout.CENTER);
032.        frame.setSize(300, 75);
033.        frame.setLocationRelativeTo(null);
034.        frame.setVisible(true);
035.    }
036.  
037.    privatestaticAccount createAccount(JFrame parent) {
038.        finalAtomicReference<Account> result = newAtomicReference<Account>();
039.        finalJDialog dialog = newJDialog(parent, "New Account", true);
040.  
041.        // Create Browser instance.
042.        finalBrowser browser = newBrowser();
043.        // Register Java callback function that will be invoked from JavaScript
044.        // when user clicks New Account button.
045.        browser.registerFunction("onCreateAccount", newBrowserFunction() {
046.            @Override
047.            publicJSValue invoke(JSValue... args) {
048.                // Read text field values received from JavaScript.
049.                String firstName = args[0].getString();
050.                String lastName = args[1].getString();
051.                String phone = args[2].getString();
052.                String email = args[3].getString();
053.                // Create a new Account instance.
054.                result.set(newAccount(firstName, lastName, phone, email));
055.                // Close dialog.
056.                dialog.setVisible(false);
057.                // Return undefined (void) to JavaScript.
058.                returnJSValue.createUndefined();
059.            }
060.        });
061.        // Load HTML with dialog's HTML+CSS+JavaScript UI.
062.        browser.loadURL("file://<;path_to_file>/index.html");
063.  
064.        dialog.addWindowListener(newWindowAdapter() {
065.            @Override
066.            publicvoidwindowClosing(WindowEvent e) {
067.                // Dispose Browser instance because we don't need it anymore.
068.                browser.dispose();
069.                // Close New Account dialog.
070.                dialog.setVisible(false);
071.                dialog.dispose();
072.            }
073.        });
074.        dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
075.        // Embed Browser Swing component into the dialog.
076.        dialog.add(newBrowserView(browser), BorderLayout.CENTER);
077.        dialog.setSize(400, 500);
078.        dialog.setResizable(false);
079.        dialog.setLocationRelativeTo(parent);
080.        dialog.setVisible(true);
081.  
082.        returnresult.get();
083.    }
084.  
085.    publicstaticclassAccount {
086.        publicfinalString firstName;
087.        publicfinalString lastName;
088.        publicfinalString phone;
089.        publicfinalString email;
090.  
091.        publicAccount(String firstName, String lastName, String phone, String email) {
092.            this.firstName = firstName;
093.            this.lastName = lastName;
094.            this.phone = phone;
095.            this.email = email;
096.        }
097.  
098.        @Override
099.        publicString toString() {
100.            return"Account{"+
101.                    "firstName='"+ firstName + '\''+
102.                    ", lastName='"+ lastName + '\''+
103.                    ", phone='"+ phone + '\''+
104.                    ", email='"+ email + '\''+
105.                    '}';
106.        }
107.    }
108. }

Now run this Java application and click New Account button:


Fill all text fields in the opened dialog and click New Account button:


Once user clicks New Account button, Java application is notified about click and reads new account information from the dialog:


Using this technique and JxBrowser library you can build and display any HTML+CSS+JavaScript UI in your Java desktop application.

Bring the power of Chromium engine into your Java desktop app!

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}