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);
    frame.setVisible(true);
  }
}

      

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"?>
<project>
  <path id="project.class.path">
    <pathelement location="build"/>
  </path>

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

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

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

      

Let's run the following jobs as expected:

ant compile
cd build/
java mypackage.Main

      

+3


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. :)

+2


source


Different goals are set here as follows:

<project>

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

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

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

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

</project>

      

And then use



ant compile
ant jar
ant run

      

Commands

+4


source







All Articles