Java
javaTutorial
JavaFX application packaging and SQLite database integration: Tutorial using jpackage
JavaFX application packaging and SQLite database integration: Tutorial using jpackage

This article details how to use the `jpackage` tool to create native installation packages for JavaFX applications and seamlessly integrate SQLite databases. Unlike traditional JAR file export, `jpackage` can package all dependencies (including JavaFX runtime and SQLite database files) into a platform-specific installation program, thereby solving the problem of database connection failure after exporting the JAR package and ensuring stable operation and resource access of the application in the desktop environment.
Challenges of JavaFX application packaging and advantages of jpackage
When developing JavaFX applications, developers often encounter a problem: when the project is exported as a JAR file, if it contains an embedded database such as SQLite, the database connection often fails. This is because the simple JAR package export method usually does not correctly handle the application's runtime dependencies, JavaFX modules, and paths to external resources (such as database files).
A traditional JAR package is essentially an executable archive file that relies on a pre-installed Java Runtime Environment (JRE) on the target system. For JavaFX applications, since the JavaFX module has been separated from the standard JDK, and its resource path management mechanism is different from that of ordinary desktop applications, directly exporting the JAR often cannot provide a complete, out-of-the-box solution.
To solve this problem, the Java platform introduced the jpackage tool. jpackage is a command-line tool available in JDK 14 and later that packages a Java application and all of its dependencies (including the JavaFX runtime, third-party libraries, and custom resources) into a platform-specific native installer (such as .msi or .exe on Windows, .dmg or .pkg on macOS, .deb or .rpm on Linux). The main advantages of using jpackage are:
- Self-contained: The packaged application contains all necessary runtime components, and users do not need to install JRE separately.
- Native experience: Generate platform-specific installers to provide an installation and launch experience consistent with operating system native applications.
- Resource Management: Ability to better manage and contain external resources required by the application, such as SQLite database files, ensuring they can be accessed correctly at runtime.
- Simplified deployment: The application deployment and distribution process is greatly simplified.
Preparation
Before you start packaging with jpackage, make sure your development environment meets the following requirements:
- JDK 14 or higher: The jpackage tool is integrated in JDK 14 and higher.
- JavaFX SDK: Make sure your project has the JavaFX SDK configured correctly. If using Maven or Gradle, please add the corresponding JavaFX dependency.
- SQLite JDBC driver: Add the SQLite JDBC driver to your project dependencies.
- Maven example:
<dependency> <groupid>org.xerial</groupid> <artifactid>sqlite-jdbc</artifactid> <version>3.44.1.0</version> <!-- Use the latest version --> </dependency>
- Maven example:
- SQLite database file: Prepare the SQLite database file you want to package (for example, samples.db). It is recommended to place it in the src/main/resources directory of the project, or in a special resources folder so that it can be included when building the JAR or processed as a resource file during the jpackage process.
Database connection code example
The following is a Java code example to connect to a SQLite database. After jpackage is packaged, the key is that the samples.db file can be located correctly.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DatabaseManager {
public static Connection getDbConnection() {
Connection dbConnect = null;
try {
//Load the SQLite JDBC driver Class.forName("org.sqlite.JDBC");
// Try to connect to the database // The "samples.db" here assumes that it is in the same directory as the application's executable file.
// Or jpackage has placed it in the application root directory dbConnect = DriverManager.getConnection("jdbc:sqlite:samples.db");
System.out.println("Opened database successfully");
} catch (ClassNotFoundException e) {
System.err.println("SQLite JDBC Driver not found: " e.getMessage());
System.exit(1);
} catch (SQLException e) {
// If the database file does not exist or the connection fails, you can try to create a new database System.err.println("Database connection failed: " e.getMessage());
// If necessary, you can call createNewDatabase("samples.db"); here
// But please note that in a production environment, the database within the application package is usually read-only.
// If writing is required, the database should be copied to a user-writable directory first.
System.exit(1);
}
return dbConnect;
}
// Example: create new database (if needed)
public static void createNewDatabase(String fileName) {
String url = "jdbc:sqlite:" fileName;
try (Connection conn = DriverManager.getConnection(url)) {
if (conn != null) {
System.out.println("A new database has been created: " fileName);
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
public static void main(String[] args) {
Connection conn = getDbConnection();
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
System.err.println("Error closing connection: " e.getMessage());
}
}
}
}
Key points: Resource path management
When packaging with jpackage, jpackage will copy the contents of the resource directory specified with the --resource-dir option to the top level of the final installation package. This means that if you place the samples.db file in a folder called resources and use --resource-dir resources in the jpackage command, samples.db will be located at the root of the application's installation directory, usually at the same level as the application's executable.
In this case, a connection string like jdbc:sqlite:samples.db usually works fine because it looks for samples.db in the application's current working directory, and the launcher generated by jpackage usually sets the application's working directory to its installation root directory.
Package JavaFX applications using jpackage
It is assumed that your JavaFX project has been built into an executable JAR file (such as your-javafx-app.jar) and that all JavaFX modules and the SQLite JDBC driver have been correctly included in it (or as module dependencies).
The following is a typical jpackage command example for packaging a JavaFX application and integrating a SQLite database:
jpackage \
--input lib\
--main-jar your-javafx-app.jar \
--main-class com.example.YourMainApp \
--name "Your JavaFX App" \
--vendor "Your Company" \
--copyright "2023 Your Company" \
--description "A JavaFX application with SQLite database." \
--icon path/to/your/icon.icns_or_ico_or_png \
--type msi \
--add-modules javafx.controls,javafx.fxml,javafx.graphics,javafx.base,javafx.media,javafx.web \
--module-path path/to/javafx-sdk/lib \
--resource-dir path/to/your/resources_folder \
--dest output
Command parameter description:
- --input lib: Specify the directory containing the application's main JAR file and all dependent libraries. Typically, you would have a lib directory that contains your-javafx-app.jar and all third-party JARs (including sqlite-jdbc-*.jar).
- --main-jar your-javafx-app.jar: Specify the application's main JAR file.
- --main-class com.example.YourMainApp: Specifies the main class of the application, that is, the class that contains the main method.
- --name "Your JavaFX App": The display name of the application.
- --vendor "Your Company": Vendor information for the application.
- --copyright "2023 Your Company": Copyright information.
- --description "A JavaFX application with SQLite database.": Application description.
- --icon path/to/your/icon.icns_or_ico_or_png: The application's icon file path. Select .icns (macOS), .ico (Windows) or .png depending on the target platform.
- --type msi: Specify the type of installer to generate. Optional values include msi, exe (Windows), dmg, pkg (macOS), deb, rpm (Linux).
- --add-modules javafx.controls,javafx.fxml,...: List all JavaFX modules required by your application.
- --module-path path/to/javafx-sdk/lib: Specifies the path to the JavaFX SDK module.
- --resource-dir path/to/your/resources_folder: This parameter is the key to integrating SQLite database. Pass the path to the directory containing the samples.db file to this option. For example, if samples.db is located in the app_resources folder in the project root, use --resource-dir app_resources. jpackage will copy all the contents of the app_resources folder to the root directory of the final installation package.
- --dest output: Specify the output directory for generating the installation package.
Build process suggestions:
- Building the project using Maven/Gradle: Ensure that your project builds successfully and generates a JAR file containing all application code and dependencies (including the SQLite JDBC driver). If using a modular project, make sure module-info.java is configured correctly.
- Prepare the resource directory: Create a dedicated directory (such as app_resources) and place the samples.db file into it.
- Run the jpackage command: Execute the above jpackage command in the command line, adjusting according to your actual project path and configuration.
Things to note
- Database read and write permissions: If your samples.db is a prepopulated database and your application needs to write to it, please note: files in the application installation directory are usually read-only. In this case, best practice is to copy samples.db from within the application package to a user-writable directory (such as the application data directory under the user's home directory) when the application first starts, and then connect to the copied database file.
- Platform compatibility: The installation packages generated by jpackage are platform specific. You need to run the jpackage command on each target operating system to generate the corresponding installation package.
- Application signing: For production applications, it is recommended to digitally sign the generated installation package to increase user trust and avoid operating system security warnings. This usually requires adding additional parameters (such as --mac-sign, etc.) to the jpackage command and configuring the corresponding signing certificate.
- JavaFX module paths: Make sure --module-path points to the correct JavaFX SDK lib directory, and --add-modules lists all JavaFX modules actually used by the application.
Summarize
With the jpackage tool, JavaFX developers can easily package applications, JavaFX runtimes, and embedded databases like SQLite into full-featured, easy-to-deploy native installers. This not only solves the problem of database connection failure after exporting the JAR package, but also greatly improves the user experience and application professionalism. Proper use of the --resource-dir option of jpackage is the key to ensuring that the SQLite database file can be correctly accessed by the application after being packaged.
The above is the detailed content of JavaFX application packaging and SQLite database integration: Tutorial using jpackage. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20524
7
13634
4
How to configure Spark distributed computing environment in Java_Java big data processing
Mar 09, 2026 pm 08:45 PM
Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre
How to safely map user-entered weekday string to integer value and implement date offset operation in Java
Mar 09, 2026 pm 09:43 PM
This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-
How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers
Mar 09, 2026 pm 09:48 PM
Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.
How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures)
Mar 09, 2026 pm 07:57 PM
After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).
What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis
Mar 09, 2026 pm 09:45 PM
ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.
Complete tutorial on reading data from file and initializing two-dimensional array in Java
Mar 09, 2026 pm 09:18 PM
This article explains in detail how to load an integer sequence in an external text file into a Java two-dimensional array according to a specified row and column structure (such as 2500×100), avoiding manual assignment or index out-of-bounds, and ensuring accurate data order and robust and reusable code.
A concise method in Java to compare whether four byte values are equal and non-zero
Mar 09, 2026 pm 09:40 PM
This article introduces several professional solutions for efficiently and safely comparing multiple byte type return values (such as getPlayer()) in Java to see if they are all equal and non-zero. We recommend two methods, StreamAPI and logical expansion, to avoid Boolean and byte mis-comparison errors.





