JAVA – How To Bundle A Java App As An Windows Executable EXE (.jar to .exe)

This question comes up time and time again and there are two programs that I frequently use to build my compiled Java apps into a Windows Executable files. This, of course, limits the environments in which your app can run to Windows only devices, so if you plan to release a ‘Windows only’ version then this could be the solution for you.

It’s worth noting that it’s also possible to bundle a jar app into a Mac OSX specific .app file, which could be something to consider if you intend to release your app to Mac OS. The .app file extension provides Mac users with a familiar file name structure which can add a subtle level of authenticity to your app. I will cover building a jar file into a Mac OS .app file in a future post.

 

So back to Windows…

 

Option 1: JSmooth (Click here to download from SourceForge)

Smooth provides a basic and easy to use interface to build your jar file into an exe. JSmoth frequently uses relative file paths, so I tend to launch within the distribution file of my compiled Java app.

The app opens on the Welcome screen, which is pretty standard. You can navigate through the pages using the menu located at the left-hand side of the screen.

Head to the Executable section
  • Executable Binary: Enter the location and file name for the exe file you wish to output. I’ve chosen to save my output file as MYAPP.exe.
  • Executable Icon: Select and icon image file to be used in your exe file. I’ve chosen to use WORLD.png located in the source of my app.
  • Current Directory:Here you can specify the working directory, your safe to leave this blank unless you implicitly wish to set it.

Head to the Application section

  • Main Class: Enter the name of the main class in your Java app, that is the main initial class called at runtime.
  • Application Arguments: You can optionally enter arguments to be passed to your app at runtime. You can enter multiple arguments separated by a comma.
  • Embedded Jar: Tick the option to Use an embedded jar and specify the name of your compiled Java .jar file. This tells JSmooth the location from which to load your .jar file.
  • Classpath: Here you must enter every external library (.jar file) included in your app. My compiled Java app has my libraries contained in a LIB folder in the same directory as my MYAPP.jar file.
    IMPORTANT
    ! The library paths are relative to your jar file AND your exe. In my example, MYAPP.exe MUST launch from a file location containing the LIB folder holding the libraries.

Head to JVM Selection

  • Minimum JVM Version: If your app requires a specific JVM version or higher, specify here.
  • Maximum JVM Version: If you wish to limit your app to run below a certain JVM, specify here.
  • Bundle JRE with your app – OPTIONAL You can optionally include a bundled Java Runtime Environment with your exe. This enables your app to run an a PC that doesn’t already have a Java installation. It also gives you control over which JVM version gets used to run your app. If the PC already has a JVM installed then your exe will use the bundled version instead of the PC version. Leave this blank to default to the installed JRE.
    Tick Use a JVM bundled with your applicationSpecify a file location, relative to your exe, which contains a full JVM.In my example, I have a folder named JRE_MASTER which contains a full JVM.
    NOTE: You may bundle a 32-BIT JVM with your exe for operation on 64-BIT OS. This could be useful if your app contains 32-BIT libraries.

Go ahead and hit the COG icon at the top of the screen. All being well, you should now have a .exe file bundled from your compile .jar file.

Smooth error messages are usually detailed enough to help locate and fix potential problems.




Option 2: Launch4j (Click here to download from SourceForge)


Launch4J is set out using a tabbed menu located at the top of the screen, opening on the Basic tab. I will describe some of the basic functions required to generate an exe and once familiar with the process you can explore the advanced functions.

 

Basic Tab

  • Output File: Enter the location and file name for the exe file you wish to output. I’ve chosen to save my output file as MYAPP.exe.
  • Jar: Specify the name of your compiled Java .jar file. This tells Launch4J the location from which to load your .jar file.
  • Icon: Select and icon image file to be used in your exe file. I’ve chosen to use WORLD.ico.
  • Java Download URL: http://java.com/download
JRE Tab
  • Bundle JRE with your app – OPTIONALYou can optionally include a bundled Java Runtime Environment with your exe. This enables your app to run an a PC that doesn’t already have a Java installation. It also gives you control over which JVM version gets used to run your app. If the PC already has a JVM installed then your exe will use the bundled version instead of the PC version. Leave this blank to default to the installed JRE.
  • Bundled JRE Path: Specify a file location, relative to your exe, which contains a full JRE.
  • Min JRE Version: If your app requires a specific JRE version or higher, specify here.
  • Max JRE Version: If you wish to limit your app to run below a certain JRE, specify here
Splash Tab
  • Launch4j provides the ability to specify a splash screen, this feature is not available in JSmooth.
  • Tick Enable splash screen
  • Splash File:Specify as location of your launch image
  • Tick Wait for window
  • Timeout [s]: Enter a timeout period in which the splash screen will disappear
Click the COG icon to generate your exe file.
IMPORTANT!: The library paths are relative to your exe. In my example, MYAPP.exe MUST launch from a file location containing the LIB folder holding the libraries. You are not required to implicitly mention each library whilst configuring your exe, as you are with JSmooth.

You should now have a runnable exe file bundled from your compile .jar file. Take some time to explore the advanced functions within the configuration menus.

Once you’re happy with your configuration you may save the settings in XML, i.e. MYAPP.XML.

You can call Launch4j from command line, specifying the XML file as follows:

”C:\Program Files (x86)\Launch4j\launch4j.exe” “C:\TMP\MYAPP.xml”

This process will auto-generate the exe file using the settings saved earlier to XML.






Java – How to scroll to a particular component in jScrollPane and gain focus

Pragmatically scrolling to a particular point in jScrollPane can be tricky, particularly if you have nested panels or layered panes. Here’s a piece of code I find myself using time and time again to have a jScrollPane scroll to a particular element and give it focus on screen.

1. Declare a JComponent and assign it the element requiring focus
JComponent comp = myTextField;
2. Adjust the vertical scroll bar to bring the component into view on screen. This is achieved by determining the Y location of the component in the scrollPane.
myScrollPane.getVerticalScrollBar().setValue(comp.getLocation().y-50);
I reduce the scroll integer value by 50 in my example to ensure the component is fully visible on screen.
3. The component is now visible on screen, so time to give focus.
comp.requestFocus();
Lets put it all together to scroll to, then give focus to, a particular component in a swing application contained in a jScrollPane.
JComponent comp = myTextField;
myScrollPane.getVerticalScrollBar().setValue(comp.getLocation().y-50);
comp.requestFocus();
If your swing application contains nested views in the scrollPane then you must call the getParent() method to move up the chain of views and establish the required scroll position.

Using the example above, lets say myTextField is contained in a jPanel, which itself is contained in the jScrollPane with an unknown Y position greater than 0.

The following code determines the Y position of the jPanel relative to the scrollPane as well as the Y position of myTextField relative to the jPanel. Sum the two values to set the scroll position.

myScrollPane.getVerticalScrollBar().setValue(comp.getParent().getLocation().y + (comp.getLocation().y – 50));
JComponent comp = myTextField;
myScrollPane.getVerticalScrollBar().setValue(comp.getParent().getLocation().y + (comp.getLocation().y – 50));
comp.requestFocus();
Next Steps…
You can manipulate the comp object’s visual properties to give the user prompts as to which field on the form has focus. I use this method to indicate a field that has failed form validation:
comp.setBackground(new java.awt.Color(255,204,204));

Java – JOptionPane with user input

A useful script to capture user input from JOptionPane:

String input = “”;

JTextField passwordField = new JTextField();

passwordField.setTransferHandler(null);

Object[] obj = {“Enter text”, passwordField};

Object stringArray[] = {“OK”, “Cancel”};

if (JOptionPane.showOptionDialog(null, obj, “Messdage with input”,
     JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, stringArray, obj) == JOptionPane.YES_OPTION) {

input = passwordField.getText();

      // TODO – USE INPUT VALUE
      System.out.println(input);
}else{
     //DO NOTHING – cancel or cross clicked
}

 

JO1

jo2

Output:

Hello World!

Java – How to add a spell checker to Swing GUI text components (JOrtho / Wikitionary)

Screen Shot 2014-11-10 at 17.16.04

This tutorial uses JOrtho, a Java based spell checker, to implement a spell checker in a Swing based application.

We are going to use an English dictionary throughout this guide, though other languages are available by downloading your language dictionary from http://www.wiktionary.org/

JOrtho (Java Orthography) is an Open Source spell-checker entirely written in Java. Its dictionaries are based on the free Wiktionary project and can therefore be updated for virtually any language. The library works with any JTextComponent from the Swing framework. This includes JTextPane, JEditorPane and JTextArea.^

 

1) Firstly, get a copy of the JOrtho libraries available here.

Once you have a copy of the zip file you’ll extract the contents and find a file named jortho.jar.

Add the jar file to your classpath or project; In Netbeans, for example, right-click your project and select Properties. Select Libraries from the Categories context menu and hit Add JAR/Folder. Navigate to the folder containing jortho.jar, select the file and click Open.

Screen Shot 2014-11-10 at 16.25.50 Screen Shot 2014-11-10 at 16.26.03

Once successfully completed you’ll see jortho.jar under the libraries node in the object explorer.

 

2) Download/Create the dictionary file for your desired language.

You can create & compile your own dictionary from data available at http://www.wiktionary.org/ with instructions found here.

Or you can simply click here to download the English dictionary I last compiled on 10/11/14:

Total Wiktionary Title count: 3,607,810
Language Title count: 464,027
Word count in dictionary: 686,426
Char count in dictionary: 6,791,818
Dictionary size on disk (bytes): 1,914,453
Dictionary size in memory (bytes): 6,058,786

 

Create a folder named dictionary within the src folder of your application (src/dictionary/) and copy in two files from the downloaded zip:

  • dictionary_en.ortho
  • dictionaries.cnf

Screen Shot 2014-11-10 at 16.27.43

Dictionaries.cnf will open in a text editor where you’ll see a comma-separated list of supported languages. Remove any languages not supported in your project.

We will change the following line: languages=de,en,it,fr,es,ru
to: languages=en

Screen Shot 2014-11-10 at 17.24.48

 

3) We can now head over to your development environment and begin coding the spell checker.

Well assume you’ve already started your project, your GUI is built and that it contains one or more text input elements on a form.

Edit your code to include the following two import statements at the head of the document:

import com.inet.jortho.SpellChecker;
import com.inet.jortho.FileUserDictionary;

Add the following lines of code to initialise and register the dictionary:

//FILE LOCATION OF DICTIONARY
String userDictionaryPath = “/dictionary/”;

//SET DICTIONARY PROVIDER FROM DICTIONARY PATH
SpellChecker.setUserDictionaryProvider(new FileUserDictionary(userDictionaryPath));

//REGISTER DICTIONARY
SpellChecker.registerDictionaries(getClass().getResource(userDictionaryPath), “en”);

Finally, register the Swing text components with the spell checker. You can register as many components as required by your application by substituting the placeholder field names with the name of your components:

SpellChecker.register(jTextField1);
SpellChecker.register(jTextArea1);
SpellChecker.register(jTextPane1);

We’ll clean things up by placing the spell checker initialisation code within a method, which we’ll call on application start up:

Screen Shot 2014-11-10 at 17.29.00

 


4) Compile & run your application!

That’s all you need to include the JOrtho spell checker in your Java Swing application. Run your app and test the theory by typing a mixture of correctly & incorrectly spelt word in the input form. Misspelt words are highlighted by a red zig-zag line underneath. Right-click on the word to reveal the pop-up suggestion list.

Screen Shot 2014-11-10 at 17.15.54

Screen Shot 2014-11-10 at 17.16.04

Screen Shot 2014-11-10 at 17.16.09

 


5) Customising the suggestion pop-up

We’re supporting only the English language in our app so we have no need to display the language selector in our pop-up menu.

I’d also like to ignore case, set a limit of 10 alternative suggestions, ignore ALL CAPS WORDS & ignore words with numb3rs – all configurable with a custom pop-up menu.

Add three more imports into your code:

import com.inet.jortho.SpellCheckerOptions;
import javax.swing.JPopupMenu;
import com.inet.jortho.PopupListener; for options when got to that part.

Initialise a SpellCheckerOtions object:

SpellCheckerOptions sco = new SpellCheckerOptions();

Configure the options as required by your application:

sco.setCaseSensitive(false);
sco.setSuggestionsLimitMenu(10);
sco.setLanguageDisableVisible(false);
sco.setIgnoreAllCapsWords(true);
sco.setIgnoreWordsWithNumbers(true);
JPopupMenu popup = SpellChecker.createCheckerPopup(sco);

Finally, add the customised pop-up menu to the components as required:

jTextField1.addMouseListener(new PopupListener(popup));

Once again, we’ll clean things up by placing the SpellCheckerOtions initialisation code within a method, which we’ll call right after initialiseSpellChecker():

Screen Shot 2014-11-10 at 17.54.34

 

You’ll notice the pop-up menu go straight into the suggestions list with the customisations described above:

Screen Shot 2014-11-10 at 17.58.08
LINKS
JOrtho 1.0 (Direct Download): http://bit.ly/1uXO7fx
English dictionary compiled – check file for creation date (Direct Download): http://bit.ly/10QlcN3
Wikitionary.org: http://www.wiktionary.org/
JOrtho: http://jortho.sourceforge.net/

^Source: http://jortho.sourceforge.net/

 

JAVA – Hot To Rename a File or Directory.

A quick script to re-name a file or folder:

Import required:

import java.io.File;

Code:

try{       
        // File name (or directory) of the file to be renamed
        File file = new File(“c:/file1.txt”);
        // New File name (or directory)
        File file2 = new File(“c:/file2.txt”);
        // Rename file (or directory)
        file.renameTo(file2);
    }catch(Exception e){
        e.printStackTrace();
    }

JAVA – How To Get The Current Directory

The following script gets the current directory at runtime:

import java.io.File;

public class CurrentDir {
   public static void main (String args[]) {
     File dir = new File (“.”);
     try {
       System.out.println (“Current Directory : ” + dir.getCanonicalPath());       }
     catch(Exception e) {
       e.printStackTrace();
       }
     }
}

The same logic can be used to get the parent to the current directory:

import java.io.File;

public class ParentDir {
   public static void main (String args[]) {
     File dir = new File (“..”);
     try {
       System.out.println (“Parent  Directory : ” + dir.getCanonicalPath());
       }
     catch(Exception e) {
       e.printStackTrace();
       }
     }
}

JAVA – JOptionPane Confirmation Dialog With YES / NO Options

This example shows how to use a JOptionPane confirmation dialog with YES / NO Options.

The response is stored in an integer variable which can be used later in the code to perform an action based on the user’s response.

You can change the button labels be changing the options [] values.

Object[] options = { “Yes”,
                            “No”};

int n =JOptionPane.showOptionDialog(null,
            “\n”
            + “Is today Monday?”
            + “\n\n”,
            “Please Confirm”,
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[1]);

       // YES OPTION CLICKED
       if(n == 0){
           System.out.println(“YES Clicked”);
       }

       // NO OPTION CLICKED
       if(n == 1){
           System.out.println(“NO Clicked”);
       }

       // CROSS CLICKED
       if(n == -1){
           System.out.println(“Cross Clicked”);
       }

Java – How To Calculate Seconds Since Midnight

Here is a simple method to calculate seconds since midnight for the current time.
There are a few methods to achieve the same result. This is a quick and easy way.

public getSecondsSinceMidnight() {         

    DateFormat dateFormat = new SimpleDateFormat();      
    java.util.Date date = new java.util.Date();

    dateFormat = new SimpleDateFormat(“HH”);
    date = new java.util.Date();
    int hour = Integer.parseInt(dateFormat.format(date));         

    dateFormat = new SimpleDateFormat(“mm”);
    date = new java.util.Date();
    int minute = Integer.parseInt(dateFormat.format(date));

    dateFormat = new SimpleDateFormat(“ss”);
    date = new java.util.Date();
    int second = Integer.parseInt(dateFormat.format(date));   

    int secondsSinceMidnight = (hour* 3600) + (minute * 60) + second;      

    System.out.println(“Current Time:” + hour + “:” + minute + “:” + second);
    System.out.print(“Seconds Since Midnight: ” + secondsSinceMidnight);                       

 }

Amongst other things, seconds since midnight can be used in calculations to establish accurate differences between 2 times.