How to run Java Swing applications with `ant run`?

For a very simple application

package mypackage;

import javax.swing.*;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(400, 400);


The following build.xml file doesn't work. The windows seem to show a very small amount of time and then the program exits.

<?xml version="1.0" encoding="utf-8"?>
  <path id="project.class.path">
    <pathelement location="build"/>

  <target name="compile" >
    <mkdir dir="build" />
    <javac srcdir="src" destdir="build" debug="true" debuglevel="lines,source">
      <classpath refid="project.class.path" />

  <target name="run" depends="compile">
    <java classname="mypackage.Main">
      <classpath refid="project.class.path" />

  <target name="clean" >
    <delete failonerror="false" verbose="true">
      <fileset dir="build" includes="**/*.class"/>


Let's run the following jobs as expected:

ant compile
cd build/
java mypackage.Main



source to share

2 answers

We figured it out eventually. Replace this line:

<java classname="mypackage.Main">


with this line:

<java classname="mypackage.Main" fork="true">


I would welcome an answer that explains in more detail why this is the case. :)



Different goals are set here as follows:


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

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

    <target name="jar">
        <mkdir dir="build/jar"/>
        <jar destfile="build/jar/YOUR.jar" basedir="build/classes">
                <attribute name="Main-Class" value="packageName.classname"/>

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



And then use

ant compile
ant jar
ant run





All Articles