About Me

My photo
Author of Groovy modules: GBench, GProf, Co-author of a Java book パーフェクトJava, Game Developer at GREE

Friday, May 4, 2012

Exploring JavaFX 2 - Accessing application parameters

JavaFX provides Application.getParameters() as a way to access application parameters from an Application class object. For example, if a user sets a width and a height as the options and a message as an argument in GNU format:
java AccessApplicationParametersDemo --width=200 --height=100 hello
the application can receive the parameters as follows:
public class AccessApplicationParametersDemo {

    public static void main(String[] args) {
        Application.launch(UsingGetParametersApplication.class, args);
    }

}
public class UsingGetParametersApplication extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Map opts = getParameters().getNamed();
        System.out.println("width=" + opts.get("width"));
        System.out.println("height=" + opts.get("height"));
        
        List args = getParameters().getUnnamed(); 
        System.out.println("message=" + args.get(0));
    }

}
But getParameters() is not functional for now (v2.2-b06) because the option parser is poor. It does not support short form options and POSIX format and it does not allow any of the following formats:
-w=200 -h=100
--width 200 --height 100
-w 200 -h 100
Should I customize getParemters()? What do you do if you hear accessing the implementation class is hard coded in it and the method is final? I mean, it is not good choice to get options or arguments directly from getParameters() for now. I recommend that you let getParameters() to act a transporter and ask Apache Commons CLI to take the main work:
public class UsingCommonsCliApplication extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Options options = new Options();
        options.addOption("w", "width", true, "");
        options.addOption("h", "height", true, "");
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(
            options, 
            getParameters().getRaw().toArray(
                new String[getParameters().getRaw().size()]
            )
        );
        System.out.println("width=" + cmd.getOptionValue("width")); 
        System.out.println("height=" + cmd.getOptionValue("height")); 
        System.out.println("message=" + cmd.getArgList().get(0));
    }

}
The problem might will be solved sooner or later because JavaFX team's answer to the problem is "We could consider this for a future version". In the first place, such a feature must be needed only by Applet or JWS that receives parameters in the fixed format, thus it seems better that JavaFX has application classes for those environments like AppletApplication or JWSApplication and make only them to have the feature.

No comments:

Post a Comment