• r8_512695
  • 1.1MB
  • zip
  • 0
  • VIP专享
  • 0
  • 2022-04-06 07:08
Java电子教程 在这个简短的教程中,我将向您展示如何在Electron,Jetty和Vaadin之上构建自己的Java桌面工具包。 入门 我们将从Gradle构建系统和Node.js安装开始。 下载并安装Gradle的最新稳定版本: ://和Node.js: : 创建一个新目录并在此目录中使用命令行运行: gradle init --type Java应用程序 Gradle将产生一组项目存根文件。 现在,您可以使用Intellij Idea或Eclipse as Java项目轻松打开目录。 让我们删除src/main/java/App.ja
# Java Electron Tutorial In this short enough tutorial I will show you how to craft your own Java Desktop toolkit on top of Electron, Jetty and Vaadin. ## Getting started We will start with Gradle build system and Node.js installation. Download and install the latest stable version of Gradle: and Node.js: Create a new directory and run using command line in this directory: > gradle init --type java-application Gradle will produce a set of project stub files. Now, you can easily open the directory using Intellij Idea or Eclipse as Java project. Let’s remove `src/main/java/` and `src/test/java/` files and open `build.gradle` file. Modify build.gradle file to match with the following: ```java apply plugin: 'java' repositories { jcenter() } dependencies { } ``` ## Vaadin UI at the speed of light Previously, I’ve already told you about our experience with Vaadin in the blog post: For me, it is battle-proven Java framework that enables us to build complex UI without a single line of HTML and JS. Let’s employ it as a basis for our UI. I will create a simple Vaadin application from scratch. First, we need to add necessary dependencies to build.gradle script, enable `war` and `gretty` plugins: ```java plugins { id 'org.akhikhl.gretty' version '2.0.0' } apply plugin: 'java' apply plugin: 'war' repositories { jcenter() } dependencies { compile 'javax.servlet:javax.servlet-api:3.0.1' compile 'com.vaadin:vaadin-server:8.1.6' compile 'com.vaadin:vaadin-push:8.1.6' compile 'com.vaadin:vaadin-client-compiled:8.1.6' compile 'com.vaadin:vaadin-themes:8.1.6' } gretty { contextPath = '/app' } ``` Refresh your Gradle project in IDE and you will be able to create UI using Vaadin. Let’s build Hello World on Vaadin. Simply create package demo and Java class AppUI inside of it. ```java @Theme(ValoTheme.THEME_NAME) public class AppUI extends UI { @Override protected void init(VaadinRequest request) { TextField nameField = new TextField(); nameField.setCaption("Your name"); Button button = new Button("Hello", event -> new Notification( "Hello " + nameField.getValue() ).show(getPage()) ); VerticalLayout content = new VerticalLayout(); content.addComponents(nameField, button); setContent(content); } } ``` As you see, we implement UI using Java API. After that, we define servlet class `demo.AppServlet`: ```java @WebServlet(urlPatterns = "/*", name = "AppServlet") @VaadinServletConfiguration(ui = AppUI.class, productionMode = false) public class AppServlet extends VaadinServlet { } ``` Finally, build and start the app using gradle: > gradle assemble jettyStart Open http://localhost:8080/app in your favorite web browser. That was easy! ![Vaadin UI](/images/image1.png) At the moment we have a pretty standard web application, it can be deployed to server or we can give it to Desktop users along with a servlet container (Tomcat, for instance) and make them use it from a web browser. ## How to embed Jetty into Java applications We will gradually transform our application into Desktop form. First step - get rid of WAR and external servlet container. Modify `build.gradle` file: ```java apply plugin: 'java' apply plugin: 'application' repositories { jcenter() } dependencies { compile 'javax.servlet:javax.servlet-api:3.0.1' compile 'com.vaadin:vaadin-server:8.1.6' compile 'com.vaadin:vaadin-push:8.1.6' compile 'com.vaadin:vaadin-client-compiled:8.1.6' compile 'com.vaadin:vaadin-themes:8.1.6' compile 'org.eclipse.jetty:jetty-server:9.3.20.v20170531' compile 'org.eclipse.jetty:jetty-webapp:9.3.20.v20170531' compile 'org.eclipse.jetty:jetty-continuation:9.3.20.v20170531' } applicationName = 'demo' mainClassName = 'demo.Launcher' ``` I’ve added jetty jars to the project dependencies and replaced `war` and `gretty` plugins with `application` plugin. The only thing left to do is to implement `demo.Launcher` class. That’s quite an easy task because the process of Jetty embedding is already described in the official manual: Thus, our Launcher will look as follows: ```java public class Launcher { public static void main(String[] args) { System.out.println("Server starting..."); ServletContextHandler contextHandler = new ServletContextHandler(null, "/", true, false); contextHandler.setSessionHandler(new SessionHandler()); contextHandler.addServlet(new ServletHolder(AppServlet.class), "/*"); Server embeddedServer = new Server(8080); embeddedServer.setHandler(contextHandler); try { embeddedServer.start(); embeddedServer.join(); } catch (Exception e) { System.err.println("Server error:\n" + e); } System.out.println("Server stopped"); } } ``` Now, we will be able to start our application as a single executable without external web server applications: > gradle run The application will be accessible on http://localhost:8080. Moreover, we can build it to a single ZIP archive with all the dependencies and distribute it to our users: > gradle distZip ## Simple Electron application A basic Electron app consists of three files: `package.json` (metadata), `main.js` (code) and `index.html` (graphical user interface). The framework is provided by the Electron executable file (electron.exe in Windows, on macOS and electron on Linux). At this stage, we will create simple electron application without our server side using Electron quick start guide: First, create `src/main/electron/package.json` file: ```json { "name" : "demo-app", "version" : "0.1.0", "main" : "main.js" } ``` We will show the stub HTML page `src/main/electron/index.html`: ```html <h1> Hello world! </h1> ``` As it is described in Electron quick start, we will use the following JS code in `src/main/electron/main.js`: ```javascript const {app, BrowserWindow} = require('electron'); const path = require('path'); const url = require('url'); let win; function createWindow() { win = new BrowserWindow({width: 800, height: 600}); win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })); win.on('closed', () => { win = null }) } app.on('ready', createWindow); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }); app.on('activate', () => { if (win === null) { createWindow() } }); ``` Now, we are ready to install electron using NPM. Go to `src/main/electron` directory and execute the following command: > npm install electron --save-dev NPM will download and install electron to your PC. Let’s start it! > npx electron ![Electron UI](/images/image2.png) At the moment, we've got all the pieces of the puzzle sitting right there on the table. Now all we have to do is put them in the right order. ## Bring all together First, simply remove src/main/electron/index.html file. We will open our application UI right on the application start. Then, build the application using Gradle and install it to the `build/install` directory: > gradle installDist Copy `build/install/demo` directory into `src/main/electron/demo`. Add +x permission for `demo/bin/demo` file if you use Mac OS or Linux. The hardest part is to start a Java process from Electron runtime and maintain the consistent state of the Java executable and a browser window. It can be done using child_process subsystem of Node.js: