JavaFX从构造函数运行。
我想使用这个类,以便只使用构造函数而不使用main方法来运行媒体文件。 (我在GUI上运行这个Player类)如果没有main方法,我如何使用luanch()
public class Player extends Application {
File file = null; // a file to play.
public Player (File file){
this.file = file;
}
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws MalformedURLException {
URL url = file.getAbsoluteFile().toURI().toURL(); // URL path of the file.
final Media m = new Media(url.toString());
final MediaPlayer mp = new MediaPlayer(m);
final MediaView mv = new MediaView(mp);
final DoubleProperty width = mv.fitWidthProperty();
final DoubleProperty height = mv.fitHeightProperty();
width.bind(Bindings.selectDouble(mv.sceneProperty(), "width"));
height.bind(Bindings.selectDouble(mv.sceneProperty(), "height"));
mv.setPreserveRatio(true);
StackPane root = new StackPane();
root.getChildren().add(mv);
final Scene scene = new Scene(root, 960, 540);
scene.setFill(Color.BLACK);
primaryStage.setScene(scene);
primaryStage.show();
mp.play();
}
}
# 1 楼答案
不确定它是否完全正确,但是调用这个提供文件的Player类的singleton怎么样
某些代码可能是(在玩家类中):
然后在另一个类中调用
# 2 楼答案
可以通过调用扩展应用程序的类的静态方法来实现。所以调用
Player.launch(Player.class)
就可以了。还要注意,不能多次调用它,否则会引发异常# 3 楼答案
Application.launch
是启动应用程序的方法。只能启动一个应用程序。使用此方法启动的任何应用程序都需要提供非arg构造函数,该构造函数在应用程序生命周期中用于构造应用程序类。不能使用自己构造的应用程序类的实例但是,您可以将
String
作为参数传递,并使用getParameters
方法访问这些参数:Player
class另类
创建一个非应用程序
Player
类,并从应用程序类中使用它。这允许您在应用程序中创建多个播放器窗口,并且或多或少独立于应用程序生命周期:使用这种方法,您还需要一个正在运行的应用程序,所以它可能是这样的: