How to build a Mac Java app (OS X 10.9+ and Java 7+)
As a quick note to self, I used the following Ant build.xml file in 2014 to build my Wikipedia Reader client application on Mac OS X 10.9 with Java 7.x:
As a quick note to self, I used the following Ant build.xml file in 2014 to build my Wikipedia Reader client application on Mac OS X 10.9 with Java 7.x:
UPDATE: The solution below worked for Java 8, and here’s a solution that works with Java 14 and newer on macOS systems.
In this article I’ll show how to build a macOS application from a Java Jar file. I tested this with Java 1.8 on macOS 10.12.5 (Sierra) on June 29, 2017.
Three assumptions in this process are:
Java Mac application FAQ: Can you share a Java/Mac Ant build script that uses the Jarbundler task to make my Java application look like a native Mac OS X application?
NOTE: This solution is for Mac OS X systems running versions of Java prior to Java 7. If I remember right, it only works on those systems, and therefore only on Mac OS X systems 10.6 and earlier. I'm working on new tutorials for Java 7 and Mac OS X 10.7, 10.8, 10.9, and newer.
UPDATE: The approach below worked with Java 8, and here is a link to the new solution for macOS and Java 14 and newer.
I wrote earlier about how to use the javapackager
command to create a macOS application bundle from a Java application, so I won’t repeat all of that information here. Instead, in this article I just want to show how to display an image that’s stored in the Contents/Resources/Java directory of a Mac/Java application bundle.
UPDATE: Please note that the approach shown below worked with Java 8, and here’s a new ‘jpackage’ tutorial for Java 14 and macOS.
I recently learned how to use the Java javapackager command to build a macOS application bundle — i.e., a regular macOS application — from a Java application. In this tutorial I’ll show how to create a Mac application bundle from a simple Java class, in this case a Java Swing class.
Java math FAQ: How do I square a number in Java?
You can square a number in Java in at least two different ways:
Math.pow
functionJava double
FAQ: How do I format Java double
and float
output to two decimal places, such as when I want to format its output for printing, or to display in a user interface? (Also, how do I do the same thing in Kotlin or Scala?)
There are at least two ways to round a double
or float
value to two decimal places in Java:
Java date/time FAQ: How do I get the current date (i.e., now or today) in Java? Also how do I get the current time in Java?
With Java 8 and newer — i.e., Java 11, 14, 17, etc. — use any of the follow “now” methods on these Java classes to get the current data and time:
I ended up not using this code, but if you wanted to see one way to use JSoup’s OutputSettings (Document.OutputSettings) class to set some parameters before calling JSoup.clean
, I hope this is helpful:
// tried some things to improve the html output val settings: OutputSettings = new OutputSettings settings.prettyPrint(true) //`true` is default settings.charset("UTF-8") settings.outline(true) //this is close to what i want, but too extreme settings.indentAmount(4) val cleanHtml: String = Jsoup.clean(html, "", wl, settings)
I can attest that this code works, it’s just not what I need at the moment.
Also, the code shown is written in Scala, but as you can see, it converts easily to Java.
Summary: This page is a printf
formatting cheat sheet or reference page. I originally created this printf
cheat sheet for my own programming purposes, and then thought it might be helpful to share it here.
A great thing about the printf
formatting syntax is that the format specifiers you can use are very similar — if not identical — between different languages, including C, C++, Java, Python, Perl, PHP, Ruby, Scala, and others. This means that your printf
knowledge is reusable, which is a good thing.
Java jar file reading FAQ: Can you show me how a Java application can read a file from own of its own Jar files?
Here's an example of some Java code I'm using to read a file (a text file) from a Java Jar file. This is useful any time you pack files and other resources into Jar files to distribute your Java application.
The source code to read a file from a Java Jar file uses the getClass and getResourceAsStream methods:
Java socket FAQ: How do I set the timeout on a Java socket? That is, when I'm trying to read data from a Java socket, and I'm not getting any response from the server, how do I make sure my code doesn't hang up? (It needs to time out after several seconds.)
Answer: Just set the SO_TIMEOUT
on your Java Socket, as shown in the following sample code:
Here's the source code for a simple JOptionPane
showMessageDialog example, where I use a JTextArea
inside of a JScrollPane
to show a long text message in the showMessageDialog:
As a quick Java tip related to lists, I was just reminded that if you need to print every element in a Java List, you can use the forEach
method on the List
:
// [1] create a List of strings. java.util.List<String> listOfStrings = CollectionConverters.asJava(xs); // [2] print the List of strings using forEach and System.out.println. // note that there is no need for a 'for' loop. listOfStrings.forEach(System.out::println);
I can confirm that as of August, 2021, this solution works just fine. So if you ever need to print every element in a Java List
— without using a for
loop — I hope this example is helpful.
Java exception FAQ: What is a Java NumberFormatException?
Answer: A Java NumberFormatException
usually occurs when you try to do something like convert a String
to a numeric value, like an int, float, double, long, etc.
The best way to show a NumberFormatException is by example, so here’s an example where I intentionally write bad Java code to throw a NumberFormatException
:
Java array FAQ: How do you create an array of Java int
values (i.e., a Java “int array”)?
Answer: There are several ways to define an int array in Java; let’s take a look at a few examples.
If you know the desired size of your array, an you'll be adding elements to your array some time later in your code, you can define a Java int array using this syntax:
I’ve been working with the Java JOptionPane showMessageDialog
a lot lately, so I thought I’d create a page here with a number of showMessageDialog
examples, sort of a JOptionPane
reference page.
I’ll walk you through some Java JOptionPane
examples here, starting with a simple example and then increasing the level of difficulty as I go on.
Java HTTPS client FAQ: Can you share some source code for a Java HTTPS client application?
Sure, here's the source code for an example Java HTTPS client program I just used to download the contents of an HTTPS (SSL) URL. I actually found some of this in a newsgroup a while ago, but I can't find the source today to give them credit, so my apologies for that.
This morning when I saw some Java JFrame
code on a mailing list, it made me think that I needed to put a simple JFrame
example out here, something that would show how to properly construct and display a JFrame without getting into a discussion of anything else. Here are two examples that show the correct technique.
To that end, here is the source code for a simple "JFrame example" demo class. This example shows how to construct a JFrame
, and make sure it's properly displayed using the SwingUtilities invokeLater
method:
As a quick note, here are some examples of the Java 8 lambda Thread and Runnable syntax. As a little bonus I also show the Java lambda syntax in other situations, such as with an ActionListener, and several “handler” examples, including when a lambda has multiple parameters.
First, here’s the lambda syntax for a Runnable
that was introduced with Java 8, and now works with Java 11, Java 14, Java 17, etc., where I create a Runnable
and pass it to a Thread
:
Runnable runnable = () -> {
// your code here ...
};
Thread t = new Thread(runnable);
t.start();
And here’s the Java Thread
lambda syntax (without a Runnable
):
Thread t = new Thread(() -> {
// your code here ...
});
You can also use this lambda approach to create a Java Thread
, without creating a reference (variable) to the thread:
new Thread(() -> // your code here).start();
Note: There’s an interesting approach documented here:
def run2() = {println("hi2")} new Thread(() => run2).start
If you can’t use Java 8+ lambdas — or don’t want to — here’s the pre-lambda thread syntax using a Runnable
:
// pre java 8 lambdas
Thread t = new Thread(new Runnable() {
public void run() {
// your code here ...
}
});
t.start();
Here’s the old Thread
syntax, using the anonymous class approach:
Thread thread = new Thread() {
public void run() {
// your code here
}
}
thread.start();
You can also create a class to extend a Thread
and then run it, like this:
public class MyThread extends Thread {
public void run() {
// your code here
}
}
MyThread myThread = new MyThread();
myTread.start();
With Java 8 lambdas this ActionListener
/ActionEvent
code:
ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { handleMakeTheImageLargerAction(); }};
can be rewritten as this:
ActionListener actionListener = actionEvent -> handleMakeTheImageLargerAction();
While I’m in the Java lambda neighborhood, here are some more examples of the Java lambda syntax, in this case showing how I use the lambda syntax for some java.awt.Desktop event handlers:
desktop.setAboutHandler(e -> JOptionPane.showMessageDialog(null, "About dialog") ); desktop.setPreferencesHandler(e -> JOptionPane.showMessageDialog(null, "Preferences dialog") ); desktop.setQuitHandler((e,r) -> { JOptionPane.showMessageDialog(null, "Quit dialog"); System.exit(0); } );
That code comes from my Java 10 on MacOS About, Preferences, and Quit handlers example.