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 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.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 name="compile" depends="clean">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes"/>

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

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


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]# ant
Buildfile: build.xml

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

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

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

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

Total 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

Leave a Reply