【问题标题】:Passing a parameter to JavaFx将参数传递给 JavaFx
【发布时间】:2014-05-30 16:34:05
【问题描述】:

我正在尝试使用 JavaFx 构建一个简单的图像查看器,其工作原理类似于:

Viewer viewer = new Viewer("path/to/file.jpg");

我已经尝试了以下代码行,但它不起作用。

public class Viewer extends Application {

private String filePath;

public Viewer(String filePath) {
    this.filePath = filePath;
}

@Override 
public void start(Stage stage) {
    // load the image
    Image image = new Image("file:" + this.filePath);

    // simple displays ImageView the image as is
    ImageView iv1 = new ImageView();
    iv1.setImage(image);

    Group root = new Group();
    Scene scene = new Scene(root);
    HBox box = new HBox();
    box.getChildren().add(iv1);
    root.getChildren().add(box);

    stage.setTitle(this.filePath);
    stage.setWidth(415);
    stage.setHeight(200);
    stage.setScene(scene); 
    stage.sizeToScene(); 
    stage.show(); 
}
}

有向 JavaFx 应用程序传递参数的标准方法吗?

【问题讨论】:

标签: java javafx


【解决方案1】:

如果我理解您的问题,您已经为您的子类应用程序传递了一个或多个参数。类抽象应用程序有一个名为 launch 的方法,它接收 String[] 参数。然后你可以为此传递一个参数,例如。 String[]{"--nameOfParameters=value of patameters",...} 。你得到getParameters().getNamed().get("name of parameters")的参数。

下面我举个例子。

public class Viewer extends Application {

        @Override 
        public void start(Stage stage) {
          // load the image
          Image image = new Image("file:" + getParameters().getNamed().get("file"));
          ...
        }

        public void caller(String[] args) {
            launch(args);
        }

        /**
         * This is a example of the passing a parameters 
         * @param args the command line arguments
         */
        public static void main(String[] args) {
             (new Viewer()).caller(new String[]{"--file=path/to/file.jpg"});
        }

    }

【讨论】:

  • 在 Java 8 中(以及早期版本的许多部署样式中),根本不调用 main(...) 方法,因此这种方法不起作用。
  • @James_D 是的,我同意你的看法。我只是测试的例子。实际上,您在程序中使用它 (new Viewer()).caller(new String[]{"--file=path/to/file.jpg"});或 (new Viewer()).launch(new String[]{"--file=path/to/file.jpg"});
【解决方案2】:

你可以简单地传递一个未命名的参数

Parameters parameters = getParameters();
List<String> unnamedParameters = parameters.getUnnamed();
filePath = unnamedParameters.get(0); // assumes path/to/file.jpg has been passed

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 2023-01-28
    • 2019-09-27
    • 1970-01-01
    • 2013-05-20
    相关资源
    最近更新 更多