01 October 2010

Java Top Tips - 2

1. Add Application Exit Logic

Swing frame windows (JFrames) automatically close themselves if you click on the close icon (the X in the corner). However, if the JFrame was the main window for your application, the application will not actually quit. After closing the window, users will need to hit Ctrl-C or whatever key sequence stops a running application on their particular platform. Worse, if the application was started with javaw, it will continue to run invisibly. There's an easy fix: shut down the application when the main window closes. It looks like this: 

       // JFrame f;
       f.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent we) { System.exit(0); }
       });

================================================================== 

2. Use the Main-class JAR Attribute

If you do package up an application in a JAR, there are two ways to run it. The first way is kind of clumsy--you have to add the JAR to your CLASSPATH and you have to know the name of the class to run. Suppose, for example, that I have an application called Shorts, packages in a JAR called Shorts.jar. To run it, I'd do something like this: 

java -cp Shorts.jar Shorts

A much nicer solution is to use the Main-class attribute, which is a way of embedding the name of the class to run inside the JAR. Then you can just run the application (in Java 2, at least) like this:
java -jar Shorts.jar
How do you do it? Normally, you would create the JAR something like this:
jar cvf Shorts.jar *.class
The trick to adding the Main-class attribute is defining an entirely separate file with the attribute definition. For instance, create the following one-line file and save it as extra.mf:
Main-class: Shorts
Now, to create the JAR, use this command line:
jar cvmf extra.mf Shorts.jar *.class
================================================================== 
 

No comments:

Post a Comment