Как сделать java приложение для windows

In this article, we will learn how to create a .exe file from a Java program. Java is a platform-independent language, which works on the philosophy of «write Once, Run Anywhere». It simply means that if we write a Java program, we can run it on any device that has a JVM(Java Virtual Machine). Now if we want to share the Java application standalone for the windows, then we need the «.exe» file. In this article first, we will create a Java program then we will see the various methods to create a «.exe» file from that file.

Java applications are generally shared and distributed as «.jar» files. These files contain all the required files, to run a .jar file we must need the JVM installed on the system we are trying to run. So what is the need for the «.exe» file, If a system does not have a JVM then we need a «.exe» file to run our application.

Steps to create a .exe file

Before creating the «.exe» file, we need to create a Java program, So let’s create a simple Java program that says hello world. Follow these steps to create and run the Java program:

Step 1: Create a file hello.java

Step 2: Open the file in any IDE, and write the following code.

Java

import java.util.Scanner;

public class Hello {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Hello, World!");
        System.out.println("Press Enter to exit...");
        scanner.nextLine();
        scanner.close();
    }
}

Step 3: Now to compile this program run the following command:

javac hello.java

Step 4: Now there will generate a file called hello.java which means that you successfully compiles, to run this program, run the following command:

java hello

Step 5: See the output in the command prompt:

Output of the Prgram

Creating .exe file

There are several methods to convert a Java application to an .exe file. Some popular methods are listed and explained below.

Now before creating the .exe file, there is one file that we need the .jar file, now when you initially create a java program it generally contains the .java and .class files, use the following commands to create the .jar file.

jar cvfe Hello.jar Hello Hello.class

Now there will be a .jar file, and we will be using that .jar file to create the .exe file using various tools that are discussed below.

1. Using JSmooth

File checks to if a suitable JVM is installed in the system or not and runs the app.

Step 1: Go to the official website of Jsmooth and download the application.
Step 2: Install the application on the system.
Step 3: Open the application, go to sell, auction, and choose the console wrapper.

Step3 Chossing the console wrapper

Step 4: Now go to the executable and give the file name that you want to create.

File Name Name od created executable

Step 5: Now go to the application first give the class name and choose the location of the .jar file

choose the location of the .jar file

Step 6: Here choose the minimum JRE version, go for 1.5.0

Step 6 choose the minimum JRE version,

Step 7: Now click on the Gear icon on the top and the .exe file will be created in chosen directory.

.exe file will be created in chosen directory

Step 8: Now double-click on the .exe file that was created, and see the output.

double-click on the .exe file that was created

2. Using Jar2Exe

This application is also used to create the .exe file from the .jar file. Follow the given steps to use this application to create the .exe file of the Java application.

Step 1: Go to the official website Jar2Exe and download the application in the system.
Step 2: Open the application, select the path of the .jar file, select the JRE version go for 1.5, and click next for the system choose windows, and click next.

Setting Path and JRE Version

Step 3: Here choose the console application and click next.

Chossing Console Application

Step 4: Here enter the class name of the Java application and click next.

Save Class Name

Step 5: Now .exe file will be created and you can run and see the output by double-clicking the .exe file.

 .exe file will be created and you can run and see the output by double-clicking the .exe file

3. Creation using Maven

To create an executable jar file for the maven projects we must have to install the maven in the system. Ensure the maven installation by running the following command.

mvn --version

Now follow the following steps to create the executable jar file. Note that we are using VS code as IDE.

Step 1: Create a maven project, use Ctrl + Shift + P, and choose the create maven project for the basic project use the maven-archtype-quickstart option as shown in the image.

Maven Project is created

Step 2: After the project creation it will create the file directory and there will be a pom.xml file for the project configuration. On that file add the following code inside the Plugins according to your project name.

XML

        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
          <configuration>
            <archive>
              <manifest>
                <addClasspath>true</addClasspath>
                <classpathPrefix>lib/</classpathPrefix>
                <mainClass>com.test.App</mainClass>
              </manifest>
            </archive>
          </configuration>
        </plugin>
        <plugin>

Step 3: Now it’s time to build the jar file. run the following command in the terminal.

nvm package

After this command, on the file directory, there will be a folder that will generate a named target, and inside that folder, there will be the .jar file. We can run this file and check by using the following command

java -jar filename.jar

Output:

Output of Program

Conclusion

In conclusion, we have seen two applications that help us to create a .exe file, and it’s pretty easy to use them. Now we can use the methods that are described above, to make the .exe file from the jar file. Follow those method steps and create the .exe file.

Последнее обновление: 20.03.2024

Итак, после установки JDK создадим первое приложение на языке Java. Что необходимо для создания программы на Java? Прежде всего нам надо написать код программы, и для этого нужен текстовый редактор.
Можно использовать любой текстовый редактор, например, Notepad++.

И чтобы превратить код программы в исполняемое приложение необходим компилятор. Компилятор устанавливается вместе с JDK.

Итак, создадим на жестком диске какой-нибудь каталог, в котором будут располагаться файлы с исходным кодом на языке Java. Допустим, это будет каталог
C:/Java. Затем создадим в этом каталоге текстовый файл, который переименуем в Program.java.
Откроем этот файл в любом текстовом редакторе и наберем в нем следующую программу:

public class Program{ 
     
    public static void main (String args[]){
         
        System.out.println("Hello METANIT.COM!");
    }
}

Java является объектно-ориентированным языком, поэтому вся программа представляется в виде набора взаимодействующих классов.
В данном случае определен один класс Program.

При определении класса вначале идет модификатор доступа public, который указывает, что данный класс будет доступен
всем, то есть мы сможем его запустить из командной строки. Далее идет ключевое слово
class, а затем название класса. То есть класс называется Program. После названия в фигурных скобках расположено содержимое класса.

Класс может содержать различные переменные и методы. В данном случае у нас объявлен один метод main.
Это главный метод в любой программе на Java, он является входной точкой программы и с него начинается все управление. Он обязательно
должен присутствовать в программе.

Метод main также имеет модификатор public. Слово static указывает, что метод main — статический, а слово void — что он не возвращает никакого значения. Позже
мы подробнее разберем, что все это значит.

Далее в скобках у нас идут параметры метода — String args[] — это массив args, который хранит значения типа String, то
есть строки. В данном случае ни нам пока не нужны, но в реальной программе это те строковые параметры, которые передаются при запуске программы из
командной строки.

После списка параметров в фигурных скобках идет тело метода — это собственно те инструкции, которые и будет выполнять метод.
В данном случае фактически определени определена только одна инструкция — вывод на консоль некоторой строки. Для вывода на консоль используется встроенный метод
System.out.println(). В этот метод передается выводимая строка. Каждая инструкция завершается точкой с запятой.

Теперь скомпилируем написанную программу. Откроем командную строку (в Windows) или терминал в Linux/MacOS и введем там соответствующие команды. Первым делом перейдем в каталог, где лежит наш файл с программой с помощью команды cd:

cd C:\Java

В данном случае файл находится в каталоге C:\Java.

Первая программа на Java на Windows

Затем cкомпилируем программу с помощью команды

javac Program.java

Компилятор языка Java представляет утилиту javac. Через пробел название нашего файла, который содержит класс программы.

После этого программа компилируется в байт-код, и в каталоге C:\Java можно будет найти новый файл Program.class.
Это и будет файл с байт-кодом программы. Теперь нам надо его запустить с помощью утилиты java:

java Program

Здесь уже расширение у файла не надо использовать.

Для ОС Windows весь процесс будет выглядеть следующим образом:

Первая программа на Java

В примере выше весь процесс разбивался на два этапа:

  1. Компилятор javac создает из программы на языке Java файл с расширением *.class, который содержит байт-код для виртуальной машины Java или JVM

  2. Утилита java запускает скомпилированный байт-код из файла с расширением *.class. То есть происходит выполнение программы

Но в последних версиях Java также стало возможно сразу выполнить код программы на языке Java:

C:\Java>java Program.java
Hello METANIT.COM!

C:\Java>

В этом случае утилите java передается файл с исходным кодом. При этом файла с расширением *.class не создается.

Let’s say you have created a Java application and packaged it into a jar.

You want to install this jar in another machine.

Traditionally , you need to first install java in that machine and then copy the jar . The application can be launched by running the jar.

Or you can use third party applications to convert the java application to an exe installation. Java itself didn’t provide this facility for a long time.

Java 8 came up with jpackage tool which can be used to create .exe files. These files can then be used to install a native Windows Application. No need to install Java in the client machine anymore!

Java again removed the tool in Java 11 version and brought it back in Java 14.

Let’s create a simple Java application which displays the message “Hello World” in a message box and convert it into an exe file. Then let’s install the application in a Windows machine.

Here is the algorithm:

STEP 1: Create the java application

STEP 2: Use ‘jar’ tool to generate a jar file

STEP 3: Use ‘jpackage’ tool to convert the jar file to exe

STEP 4: Install the exe file on a Windows machine

STEP 1: Create the java application :

I created a Java application with a single file which opens up a message box with the message “Hello World”.

Here is the code:

package com.helloworld;

import javax.swing.*;

public class Main {

    public static void main(String[] args) {


        JOptionPane.showMessageDialog(null, "Hello World", "A Windows Application", JOptionPane.INFORMATION_MESSAGE);

    }
}

On running this , I get the below output:

Now let’s convert this project into a jar file

STEP 2: Use ‘jar’ tool to generate a jar file

Below is the path where I have created the Java application:

G:\projects\fullstackdeveloperblog\spring\springboot\HelloWorld\

On building the project the classes got generated in out/production folder ( I am using IntelliJ):

G:\projects\fullstackdeveloperblog\spring\springboot\HelloWorld\out\production

A new folder named HelloWorld got generated in the above directory.

I navigated inside it and ran the below jar command:

jar cfm helloworld.jar manifest.txt com

helloworld.jar is the name of the jar file to generate

manifest.txt contains meta data about the jar (what is the path of the main class etc)

com is the directory (inside HelloWorld folder) which contains the Main class

To know more about generating jar files refer here : (Generating jar)

A jar file got generated as below:

If you double click the jar file you get the same output:

STEP 3: Use ‘jpackage’ tool to convert the jar file to exe

As a prerequisite to run jpackage tool to generate a exe file , you need to install Wix Toolset (suggested by Java) from here .

In the same path where I ran ‘jar’ command I ran the below jpackage command:

jpackage --name helloworld --input . --main-jar helloworld.jar --main-class com.helloworld.Main --win-console

Following –name is the name of the exe file

Following –input (.) is the name of the directory which contains the jar file and other inputs (in this case the current directory)

Following –main-jar is the name of the jar which contains the class to be run

Following –main-class is the name of the class which is to be run.

–win-console means windows console need to be enabled – Command line and Java swing applications need this to be enabled.

–win-console flag is quite important. It took me a while to realise this was needed (Else application won’t be launched when you click on the installed exe)

Here is the screenshot of running the jar and jpackage commands:

Below is the exe file generated:

STEP 4: Install the exe file on a Windows machine

Now let’s install the application using the exe file created.

Double click on helloworld-1.0.exe.

The application gets installed :

It gets installed in the default C:/Program Files directory:

Go into the folder and click on helloworld.exe:

Hello World message is shown!

Now let’s try to execute this exe file through command prompt from any path in Windows machine.

For this to happen , add the path of the exe to the ‘PATH’ environment variable of your machine:

Now go to any path in the command prompt and enter helloworld:

We have created a native windows application!

As said earlier by default it gets installed in C:/Program Files directory .To prompt the user to provide the path while installation add the flag –win-dir-chooser to jpackage command:

jpackage --name helloworld --input . --main-jar helloworld.jar --main-class com.helloworld.Main --win-console --win-dir-chooser

If you want to create a short cut in the desktop once your application is installed add the flag –win-shortcut to the above command:

jpackage --name helloworld --input . --main-jar helloworld.jar --main-class com.helloworld.Main --win-console --win-dir-chooser --win-shortcut

If you want to create a menu under the Start Menu add two flags –win-menu –win-menu-group and against –win-menu-group provide the name of the menu you want:

jpackage --name helloworld --input . --main-jar helloworld.jar --main-class com.helloworld.Main --win-console --win-dir-chooser --win-shortcut --win-menu --win-menu-group "Hello World"

If you want to provide an icon for your application , use –icon flag. Copy the icon file in the same directory where you are running jpackage command.

jpackage --name helloworld --input . --main-jar helloworld.jar --main-class com.helloworld.Main --win-console --win-dir-chooser --win-shortcut --win-menu --win-menu-group "Hello World" --icon helloworldicon.ico

Let’s run jpackage tool with all the above options and create an exe installation file.

Now if you run the generated exe file it will prompt you for installation directory:

Once successfully installed , go to your desktop and notice a short cut created with the icon you chose. Double click the file and Hello World message gets displayed!

Go to start menu and notice the app “Hello World”:

Creating a Windows Native Application in Java got easier and cooler.

Launch4j is a cross-platform tool for wrapping Java applications distributed as jars in lightweight Windows native executable files. In this post, we will learn making such an executable file for a demo java application.

Step1 ) Create a java application

I am creating a very basic java class which simply displays a frame and some text on it. It also has the main() method which will start the application.

package com.howtodoinjava;

import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JDialog;

public class ApplicationMain extends JDialog 
{
	private static final long serialVersionUID = 1L;
	public ApplicationMain() 
	{
		//Create a frame
		Frame f = new Frame();
		f.setSize(500, 300);
		
		//Prepare font
		Font font = new Font( "SansSerif", Font.PLAIN, 22 );
		
		//Write something
		Label label = new Label("Launch4j Maven Demo with HowToDoInJava.com");
		label.setForeground(Color.RED);
		label.setFont(font);
		f.add(label);

		//Make visible
		f.setVisible(true);
		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}
	public static void main(final String[] args) 
	{
		new ApplicationMain();
	}
}

Step 2) Create maven file with launch4j configured in it

I have created a pom file for packaging the application as .exe file. If you feel something unclear, drop a comment.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.howtodoinjava</groupId>
  <artifactId>JavaExeDemo</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>JavaExeDemo</name>
  <url>http://maven.apache.org</url>
  <properties>
	    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.5.1</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>1.7.1</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <shadedArtifactAttached>true</shadedArtifactAttached>
                <shadedClassifierName>shaded</shadedClassifierName>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>com.howtodoinjava.Main</mainClass>
                    </transformer>
                </transformers>
            </configuration>
        </plugin>
        <plugin>
            <groupId>com.akathist.maven.plugins.launch4j</groupId>
            <artifactId>launch4j-maven-plugin</artifactId>
            <version>1.5.1</version>
            <executions>
                <execution>
                    <id>l4j-clui</id>
                    <phase>package</phase>
                    <goals>
                        <goal>launch4j</goal>
                    </goals>
                    <configuration>
                        <headerType>gui</headerType>
                        <jar>${project.build.directory}/${artifactId}-${version}-shaded.jar</jar>
                        <outfile>${project.build.directory}/howtodoinjava.exe</outfile>
                        <downloadUrl>http://java.com/download</downloadUrl>
                        <classPath>
                            <mainClass>com.howtodoinjava.ApplicationMain</mainClass>
                            <preCp>anything</preCp>
                        </classPath>
                        <icon>application.ico</icon>
                        <jre>
                            <minVersion>1.6.0</minVersion>
                            <jdkPreference>preferJre</jdkPreference>
                        </jre>
                        <versionInfo>
                            <fileVersion>1.0.0.0</fileVersion>
                            <txtFileVersion>${project.version}</txtFileVersion>
                            <fileDescription>${project.name}</fileDescription>
                            <copyright>2012 howtodoinjava.com</copyright>
                            <productVersion>1.0.0.0</productVersion>
                            <txtProductVersion>1.0.0.0</txtProductVersion>
                            <productName>${project.name}</productName>
                            <companyName>howtodoinjava.com</companyName>
                            <internalName>howtodoinjava</internalName>
                            <originalFilename>howtodoinjava.exe</originalFilename>
                        </versionInfo>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</project>

Step 3) Create .exe file

To make the exe file for above java program, run maven command:

mvn package

Above command will create the “howtodoinjava.exe ” file in your project’s target folder. Double click on .exe file will open the window like this.

Launch4j maven demo to create java executable

Launch4j maven demo to create java executable

If you want to download source code of above application, click on below given download link.

Sourcecode Download

Happy Learning !!

by: Ethan McCue

Double-click to run is one of the easiest ways to open a program.

If the person you are sharing code with already has the right version of Java installed, they can double-click on a jar file to run it. You wrote it once, they can run it there.

If they don’t have Java installed, then there are ways to create a runnable installer like jpackage, but now they have to click through an installer to be able to run your code.

You can use Native Image to turn your code into an exe which won’t require them to have anything installed, but now you have to abide by the closed world assumption and that’s not always easy or possible.

So this post is going to focus on a fairly oonga boonga approach that will work for any app, regardless of what dependencies you include or JVM features you make use of.

The code along with an example GitHub workflow can be found in this repo and final executables can be found here.

Prerequisites

Java 9+

java --version
jlink --version

Maven

NodeJS

Step 1. Compile and Package your code into a jar.

This toy program will create a basic window that has some text that you can toggle between being capitalized.

package example;

import org.apache.commons.text.WordUtils;

import javax.swing.*;
import java.awt.*;

public class Main {
    public static void main(String[] args) {
        var label = new JLabel("Hello, World!");
        label.setFont(new Font("Serif", Font.PLAIN, 72));

        var uppercaseButton = new JButton("Uppercase");
        uppercaseButton.addActionListener(e ->
            label.setText(WordUtils.capitalize(label.getText()))
        );

        var lowercaseButton = new JButton("lowercase");
        lowercaseButton.addActionListener(e ->
            label.setText(WordUtils.uncapitalize(label.getText()))
        );

        var panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(label);
        panel.add(uppercaseButton);
        panel.add(lowercaseButton);

        var frame = new JFrame("Basic Program");
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

Program Demonstration

The goal is to package up your code, along with its dependencies, into a jar. Jars are just zip files with a little extra structure.

For a Maven project the configuration will look like the following.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>example</groupId>
    <artifactId>javaexe</artifactId>
    <version>1.0</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>18</maven.compiler.source>
        <maven.compiler.target>18</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.9</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <Main-Class>example.Main</Main-Class>
                                        <Build-Number>1.0</Build-Number>
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Where the «shade» plugin will handle including the code from all of your dependencies into the jar. In this case, the only external dependency is org.apache.commons/commons-text.

Then for the purposes of this guide we will move that jar into a new directory where it will be separate from whatever other files are in target/.

mkdir build 
mv target/javaexe-1.0.jar build

Step 2. Create a Java Runtime Environment

In order to run the jar from the previous step, we will need to bundle it with a Java Runtime Environment. To do this we will use jlink.

Since the Java ecosystem hasn’t embraced modules, you most likely haven’t heard of or used jlink.

The short pitch is that it can create «custom runtime images.» Say you are making a web server. You don’t need AWT or Swing, so including all the code for that is a tad wasteful. With jlink you can make a JRE that doesn’t include the java.desktop module at all.

This system works best if your application and all of its dependencies include compiled module-info.java files which let jlink know exactly what modules you want to include. You can also manually figure out the list of required modules by using jdeps and a bit of detective work.

Even without a modular project though, we can still use jlink to effectively clone our Java installation to a directory.

jlink --add-modules ALL-MODULE-PATH --output build/runtime

Including every module gives confidence that libraries like org.apache.commons/commons-text will work as intended, even though we never figured out what modules they actually require.

Step 3. Bundle the Jar and the JRE into an executable

So with a jar containing our code and all of its dependencies in one hand and a JRE in the other, all that’s left is to stitch the two together.

The general technique for that is to

  1. Zip up the directory containing the JRE and your application jar.
  2. Attach a stub script to the top of that zip file which will extract the zip to a temporary directory and run the code.

There is a JavaScript library which does this called caxa. Its purpose is making NodeJS projects into executables, so it will also bundle whatever NodeJS installation is on the system. That step can luckily be skipped by passing the --no-include-node flag, so it will work just fine for this.

npx caxa \
    --input build \
    --output application \
    --no-include-node \
    -- "{{caxa}}/runtime/bin/java" "-jar" "{{caxa}}/javaexe-1.0.jar"

This will create an executable called «application.» If you are doing this for Windows you should specify «application.exe.» When the executable is run the {{caxa}}s in the command will be substituted for to the temporary directory where the zip file was expanded.


I am aware of jdeploy — and it does handle stuff that I didn’t cover or would be relatively hard with this scheme like code signing or automatic updates — but as far as I can tell it still requires that users run an installer.

On code signing, there is an open issue with caxa to figure out how to do that. I can make another post or update this one if an approach is figured out. I don’t quite understand the issue, so I don’t feel qualified to comment.

If any mildly ambitious reader wants to try their hand at making caxa in a different language so this process isn’t dependent on the JS ecosystem I encourage it.

As always, comments and corrections welcome.


<- Index

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Google chrome windows 7 old version
  • Прописывание маршрутов в windows
  • Включить smb windows server 2019
  • Windows error reporting service перевод
  • Установка служб удаленных рабочих столов windows server 2019 powershell