简体   繁体   中英

Command line arguments in JavaFX

So I have to draw N rectangles between the values min and max. I have the code working to draw the rectangles. However, I can't figure out how to give it the command-line arguments N, min and max. This is what I have

import javafx.application.Application;
import javafx.scene.layout.AnchorPane;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class testRect extends Application {

@Override
public void start(Stage Stage) throws Exception {

    AnchorPane root = new AnchorPane();
    Scene scene = new Scene(root, 500, 500, Color.LIGHTGREY);
    Stage.setScene(scene);

    int N = Integer.parseInt(args[0]);
    int min = Integer.parseInt(args[1]);
    int max = Integer.parseInt(args[2]);
    int interval = ((max - min)/ (N-1));
    Rectangle r = null;
    while(min < max + 1){
        for(int i = 0; i < N; i++) {
            r = new Rectangle(100, 100, min, min);
            r.setFill(Color.TRANSPARENT);
            r.setStroke(Color.BLACK);
            root.getChildren().add(r);
            min = min + interval;
        }
    }
    scene.setRoot(root);
    Stage.show();
}
public static void main(String[] args) {
    launch(args);
}

}

it works when I directly give N, min and max values. But I'm not sure how to do it with the command line.

The command line arguments are available to a JavaFX Application via the getParameters method defined in Application .

For "unnamed" parameters, such as those that would be provided by invoking your application with

java testRect 10 0 100

you would do

int N = Integer.parseInt(getParameters().getUnnamed().get(0));
int min = Integer.parseInt(getParameters().getUnnamed().get(1));
int max = Integer.parseInt(getParameters().getUnnamed().get(2));

You can also pass named parameters:

java testRect --N=10 --min=0 --max=100

which you would retrieve with

int N = Integer.parseInt(getParameters().getNamed().get("N"));
int min = Integer.parseInt(getParameters().getNamed().get("min"));
int max = Integer.parseInt(getParameters().getNamed().get("max"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM