Ant: Java Swing Hello World in Ant

This is the fifth part of the so called Ant series I have been writing in this blog, about Apache Ant. This post is mainly about building and running a Java Swing program using Ant.

The previous posts on Ant can be found here:

1. Apache Ant
2. Ant: Installation
3. Ant: Hello World in Ant
4. Ant: Java Hello World in Ant


Java Swing Program

Create the following simple swing program and save it as HelloWorldSwing.java in a sub folder src:

import javax.swing.JFrame;import javax.swing.JLabel;

public class HelloWorldSwing {public static void main(String[] args) {JFrame frame = new JFrame("HelloWorldSwing");final JLabel label = new JLabel("Hello World");frame.getContentPane().add(label);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.pack();frame.setVisible(true);   }}

Ant Script

Use a text editor to create a file called build.xml and place it in the main folder:

<?xml version="1.0" encoding="UTF-8"?><project name="Run Test" default="run" basedir=".">

<target name="clean">   <delete dir="build"/></target>

<target name="compile" depends="clean">   <mkdir dir="build/classes"/>   <javac srcdir="src" destdir="build/classes"/></target>

<target name="jar" depends="compile">   <mkdir dir="build/jar"/>   <jar destfile="build/jar/HelloWorldSwing.jar" basedir="build/classes">       <manifest>           <attribute name="Main-Class" value="HelloWorldSwing"/>       </manifest>   </jar></target>

<target name="run" depends="jar">   <java jar="build/jar/HelloWorldSwing.jar" fork="true"/></target>

</project>

Outputs and Problems

When we run this is text mode it, it compiles but fails to run. But when in GUI it runs.

[root@sanjaya-vm ant-swing]# antBuildfile: build.xml

clean:[delete] Deleting directory /opt/ant-swing/build

compile:[mkdir] Created dir: /opt/ant-swing/build/classes[javac] Warning: HelloWorldSwing.java modified in the future.[javac] Compiling 1 source file to /opt/ant-swing/build/classes

jar:[mkdir] Created dir: /opt/ant-swing/build/jar[jar] Building jar: /opt/ant-swing/build/jar/HelloWorldSwing.jar

run:......[java] at java.awt.Window.<init>(Window.java:406)[java] at java.awt.Frame.<init>(Frame.java:402)[java] at javax.swing.JFrame.<init>(JFrame.java:207)[java] at HelloWorldSwing.main(Unknown Source)[java] Java Result: 1

BUILD SUCCESSFULTotal time: 3 seconds

This is one another basic level post and I strongly advice you to refer to any more advanced document, if you are going to do this for any production system. :)

Feedback and questions are welcome via comment or you can email me at talkout AT SPAMFREE gmail DOT com

This entry was posted in Tech Notes and tagged , . Bookmark the permalink.

Comments are closed.