# 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
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
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 (18个子文件)
java-electron-tutorial-master
.gitignore 67B
images
image3.png 20KB
image1.png 15KB
image4.png 1.02MB
image2.png 21KB
settings.gradle 583B
build.gradle 665B
src
main
electron
package.json 214B
main.js 2KB
package-lock.json 41KB
java
demo
AppServlet.java 354B
Launcher.java 974B
AppUI.java 3KB
gradlew 5KB
README.md 16KB
gradlew.bat 2KB
gradle
wrapper
gradle-wrapper.properties 233B
gradle-wrapper.jar 53KB
共 18 条
- 1
橘子乔JVZI
- 粉丝: 28
- 资源: 4580
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0