Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run Java Swing applications using `ant run`?

Tags:

java

swing

ant

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. It seems that the windows shows for 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>

But running the following works as expected:

ant compile
cd build/
java mypackage.Main
like image 741
Andres Riofrio Avatar asked Feb 21 '23 03:02

Andres Riofrio


1 Answers

Here it is Define different targets 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

like image 78
Rahul Borkar Avatar answered Mar 07 '23 13:03

Rahul Borkar