如何从另一个 Java 文件调用 Java 文件

How to call the Java file from another Java file

我在调用我从另一个包含 UI 元素的 Java 文件创建的 Java 文件时遇到了困难。这是我要调用的 Java 代码:

public class XzibitVideo extends Application{

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

    @Override
    public void start(Stage stage) {
        String path = "Data/Video/Clip.flv";
        Media media = new Media(new File(path).toURI().toString());

        MediaPlayer mediaPlayer = new MediaPlayer(media);
        MediaView mediaView = new MediaView(mediaPlayer);

        BorderPane borderPane = new BorderPane();
        borderPane.setCenter(mediaView);
        //borderPane.setStyle("-fx-background-color: Black");
        //borderPane.setBottom(addToolBar());

        Scene scene = new Scene(borderPane, 1024, 800);
        scene.setFill(javafx.scene.paint.Color.BLACK);

        stage.setTitle("Media Player");
        stage.setScene(scene);
        stage.show();

        mediaPlayer.setAutoPlay(true);
        mediaPlayer.setOnError(()->System.out.println("media error"+ mediaPlayer.getError().toString()));
    }
}

我已经尝试了几种方法来调用它,但恐怕 none 中的方法都有效。例如,

XzibitVideo programVideo = new XzibitVideo();
programVideo.start();

XzibitVideo programVideo = new XzibitVideo();
programVideo.run();

XzibitVideo programVideo = new XzibitVideo();
programVideo.main();

*我也试过添加 arguements/parameters,但没有成功:

XzibitVideo programVideo = new XzibitVideo();
programVideo.start(Stage stage);

如果有人知道如何正确调用此函数,我将不胜感激!我在这部分工作的时间太长了,我失去了所有的希望..:(

CLASSPATH 定义查找 classes 的位置。您可以将 CLASSPATH 设置为环境变量(以某种方式取决于您的 OS),或者您可以在调用 Java.

时为其提供命令行参数 class 文件可以在另一个目录中,或者在 JAR 中 - 无论如何你必须使用 CLASSPATH 指向它。

尝试:

Stage stage = new Stage(); // or using another constructor of class Stage
XzibitVideo programVideo = new XzibitVideo();
programVideo.start(stage);

我认为这应该可行:

    XzibitVideo programVideo = new XzibitVideo();
    programVideo.launch(XzibitVideo.class);
    this.dispose();

您可以使用

从另一个 class 启动应用程序
Application.launch(XzibitVideo.class);

注:

  1. 此方法将阻塞,直到 JavaFX 平台退出
  2. 每个应用程序只能调用一次 launch()(即每个 JVM 生命周期一次)

不太清楚你为什么要这样做。 Application subclass 中的 start() 方法(顾名思义)是应用程序的起点。 main 方法甚至仅包含在 JavaFX 应用程序中,以便运行时环境无法原生启动 JavaFX 应用程序 classes。因此,Application subclasses 本质上是不可重用的。如果您希望 XzibitVideo 可重用,您应该重构它,使其不是 Application 的子 class,并且只需创建一个简单的 Application 子class谁的 start() 方法引用了它。