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.






Advertisements

SQL Server SSMS Saving changes is not permitted

You may receive this dialogue if you’re using a fresh install of SSMS, or after an upgrade. It simply means your environment hasn’t been configured to allow certain changes which require the dropping, and re-creation, of a table.

Such actions include:

  • Adding a new column anywhere other than the end of a table
  • Deleting a column
  • Updating column configuration, such as Allow Nulls or the Data Type
  • Changing the column order

You can modify your environmental settings to allow for these actions form the Tools menu. Click Options, expand Designers, and then click Table and Database Designers. Un-tick Prevent saving changes that require the table to be re-created and click OK.

You may now commit your table changes.

 

SQL – How to Update and Select in the same query

The OUTPUT clause Returns information on each row affected by an INSERT, UPDATE, DELETE, or MERGE statement.

These results can be returned to the processing application for further use.

The following example uses the OUTPUT clause to return row values in conjunction with an UPDATE query which effectively enables a SELECT and UPDATE command in the same query.
 
— CREATE TEMP TABLE
CREATE TABLE #TempTable ( URN INT, F1 VARCHAR( 50), F2 VARCHAR(50 ), USED VARCHAR (1))
— INSERT DATA
insert into #TempTable values ( 1,’F1_Val_1′ ,’F2_val_1′, ‘N’)
insert into #TempTable values ( 2,’F1_Val_2′ ,’F2_val_2′, ‘N’)
insert into #TempTable values ( 3,’F1_Val_3′ ,’F2_val_3′, ‘N’)

— UPDATE SINGLE ROW IN TABLE WITH NEW VALUE
— USING OUTPUT COMMAND TO RETURN FIELDS OF UPDATED ROW
UPDATE #TempTable
SET F1 = ‘F1_New_Val’
OUTPUT Inserted.URN, Inserted.F1, Inserted.F2
WHERE URN = 1

— UPDATE MULTIPLE ROWS IN TABLE WITH NEW VALUE
— USING OUTPUT COMMAND TO RETURN FIELDS OF UPDATED ROWS
UPDATE #TempTable
SET F1 = ‘F1_And_F3_new_Val’
OUTPUT Inserted.URN, Inserted.F1, Inserted.F2
WHERE URN in (1 ,3)

— UPDATE ALL ROWS IN TABLE WITH NEW VALUE
— USING OUTPUT COMMAND TO RETURN FIELDS OF ALL ROWS IN TABLE
UPDATE #TempTable
SET F1 = ‘New_Global_Val’
OUTPUT Inserted.URN, Inserted.F1, Inserted.F2

— UPDATE TOP 1 ROW IN TABLE WITH NEW VALUE
— MARK USED = ‘Y’
— USING OUTPUT COMMAND TO RETURN FIELDS OF UPDATED ROW
UPDATE #TempTable
SET F1   = ‘F1_New_Val’
,USED = ‘Y’
OUTPUT Inserted.URN, Inserted.F1, Inserted.F2
WHERE URN in (select max( URN) from #TempTable WHERE used = ‘N’)

— DROP TEMP TABLE
DROP TABLE #TempTable

 

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));

Mac – How to remove uninvited Google apps from launchpad

Screen Shot 2015-06-22 at 21.20.30

At the time of writing this, you get stuck with a bunch of Google apps added to your Mac’s Launchpad when you install Google Chrome.

These are:

  • Google Chrome (to be expected)
  • Google Drive
  • Gmail
  • YouTube and
  • Google Search

I found this to be annoyingly intrusive and a modification that I didn’t ask for nor agree to. I found it even more frustrating that you don’t simply navigate to your Applications folder to remove the uninvited guests.

Instead, you must navigate  to your users folder (Right-click on finder icon –> Go To Folder… –> enter forward slash [/] hit enter), enter your user account folder, find the Applications sub-folder and here we find a new folder named Chrome Apps.

Deleting the Chrome Apps folder removes the icons from Launchpad.

Register ActiveX DLL or OCX Files on 64-BIT Windows

regsvr32 c:\WINDOWS\system32\WebAgent4.ocx
Screenshot 2015-06-17 13.52.17

 

If you receive an error when registering a 32-bit DLL or OCX on a 64-bit version of Windows, follow these steps:

 

1. Open an elevated command prompt – its important the command window has Administrator access otherwise you will continue to see errors:

 

in Windows Vista or 7:
Select Start > All Programs > Accessories
Right-click on “Command Prompt” in the Accessories
Click “Run as Administrator”

 

in Windows 8:
Open the “Quick Link” menu (by holding down the Windows 8 logo key  and pressing the X key)
Select “Command Prompt (Admin)”
Select “Yes” to allow changes

 

2. If the 32-bit DLL or OCX is in the %systemroot%\System32 folder, move it to the %systemroot%\SysWoW64 folder.

 

3.Run the following command:
%systemroot%\SysWoW64\regsvr32 <full path of the DLL or OCX>


In my example this would be: %systemroot%\SysWOW64\regsvr32 C:\Windows\SysWOW64\WebAgent4.OCX
Screenshot 2015-06-17 13.56.25


^Source: https://support.microsoft.com/en-us/kb/249873

iOS / Objective-c – Simple NSTimer

Here’s a simple use of NSTimer to repeatedly trigger a method call every X seconds in Objective-c, for iOS.

Declare NSTimer variable in header file

NSTimer *myTimer;

Initialise myTimer at the appropriate point in code. Could be viewDidLoad on iPhone or willActivate on Apple Watch. My example triggers the method named updateDisplay at 5 second intervals. Note that I’ve set repeats: YES.
You can trigger the method for a one off call after X seconds by setting repeats: NO.

myTimer= [NSTimerscheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(updateDisplay)
userInfo:nil
repeats:YES];

The above code both primes and starts the timer.

To end the timer. Could be didDeactivate on apple Watch, for example

[myTimer invalidate];
myTimer = nil;

How to take a screenshot on Apple Watch

It’s a little tricky but you can take a screenshot on Apple Watch, handy when you want a live shot of an app your developing. Or perhaps you want a lasting reminder of some notification or other. Either way, follow these steps:

1. Get a good grip of your Apple watch.

If you wear with the side buttons facing your hand:

Placing your thumb on the smooth side
Rest your first finger over the digital crown
Rest your middle finger on the side button

If you wear with the side buttons facing your elbow:

Placing your first finger on the smooth side
Rest your thumb over the digital crown and the side button

2. Press the digital crown and side button at the same time.

The two buttons pressed at the same time will result in a screenshot of the current display. A flash of the screen accompanied by the camera shutter sound signifies a successful screenshot.

3. View and share the image

The screenshot from your Apple watch is saved to the paired iPhones camera roll. Open photos on iPhone to view your screenshot. Tap the share button to view the options.

IMG_7954

P.S. you can see the full Apple Watch user guide here: apple.co/1IPuZoa

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!

SQL – View SQL Server Database Mail Log (All / Successful / Failed)

SQL Server keeps a log of mail sent via Database Mail and the sp_send_dbmail Stored Procedure.

I find these code snippets useful to view mail history including sent and failed items. You can view address, subject & body, file attachment(s), status, sent date, etc.

All Messages – regardless of status and deliverability
SELECT top 50 *
FROM [msdb].[dbo].[sysmail_allitems]
ORDER BY [send_request_date] DESC
Sent Items
SELECT TOP 50 *
FROM [msdb].[dbo].[sysmail_sentitems]
ORDER BY [send_request_date] DESC
Failed Items
SELECT TOP 50 *
FROM [msdb].[dbo].[sysmail_faileditems]
ORDER BY [send_request_date] DESC