java-electron-tutorial:如何使用Electron构建Java桌面应用程序

  • r8_512695
    了解作者
  • 1.1MB
    文件大小
  • zip
    文件格式
  • 0
    收藏次数
  • VIP专享
    资源类型
  • 0
    下载次数
  • 2022-04-06 07:08
    上传日期
Java电子教程 在这个简短的教程中,我将向您展示如何在Electron,Jetty和Vaadin之上构建自己的Java桌面工具包。 入门 我们将从Gradle构建系统和Node.js安装开始。 下载并安装Gradle的最新稳定版本: ://gradle.org/releases/和Node.js: : 创建一个新目录并在此目录中使用命令行运行: gradle init --type Java应用程序 Gradle将产生一组项目存根文件。 现在,您可以使用Intellij Idea或Eclipse as Java项目轻松打开目录。 让我们删除src/main/java/App.ja
java-electron-tutorial-master.zip
内容介绍
# 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: https://gradle.org/releases/ and Node.js: https://nodejs.org/en/download/ 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/App.java` and `src/test/java/AppTest.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: https://vaadin.com/blog/cuba-studio-how-we-use-vaadin-for-our-web-development-tool 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: http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html 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, electron.app on macOS and electron on Linux). At this stage, we will create simple electron application without our server side using Electron quick start guide: https://github.com/electron/electron/blob/master/docs/tutorial/quick-start.md. 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: https://nodejs.org/api/child_proces
评论
    相关推荐