我想创建一个 Singleton JavaFX 中的主类但我遇到了困难,因为主类必须扩展 Application ,所以构造函数不能是私有(private)的。
我希望主类是单例,因为我想从任何类访问几个实例方法。
在我当前的代码中,我将主类用作伪单例,因为我不保证该类不会在代码的某些部分再次实例化。
我想知道当您不能使用私有(private)构造函数时,是否有一种合适的方法来创建单例。
这是我的主类的代码:
public final class MainClass extends Application {
private static MainClass instance;
private Stage primaryStage, optionsStage;
@Override
public void start(final Stage primaryStage) {
instance = this;
try {
// Main scene.
{
Parent page = (Parent) FXMLLoader.load(
MainWindowController.class.getResource("main.fxml"));
Scene mainScene = new Scene(page);
primaryStage.setScene(mainScene);
primaryStage.show();
}
// Options scene.
{
optionsStage = new Stage();
optionsStage.setTitle("Options");
optionsStage.setResizable(false);
optionsStage.initModality(Modality.APPLICATION_MODAL);
optionsStage.initOwner(primaryStage);
Parent page = (Parent) FXMLLoader.load(
OptionsWindowController.class.getResource("options.fxml"));
Scene scene = new Scene(page);
optionsStage.setScene(scene);
}
} catch (Exception ex) {
Constants.LOGGER.log(Level.SEVERE, ex.toString());
}
}
/**
* Returns the instance of this class.
* @return
*/
public static MainClass getInstance() {
return instance;
}
public Stage getPrimaryStage() {
return primaryStage;
}
/**
* Returns the options stage.
* @return
*/
public Stage getOptionsStage() {
return optionsStage;
}
/**
* The main() method is ignored in correctly deployed JavaFX
* application. main() serves only as fallback in case the
* application can not be launched through deployment artifacts,
* e.g., in IDEs with limited FX support. NetBeans ignores main().
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
最佳答案
我认为添加如下所示的公共(public)构造函数并删除 start
方法中的 instance = this;
赋值可以解决问题,尽管我不是精通JavaFX。我认为它不会多次尝试实例化您的主类,但如果 API 不提供此类保证,您以后可能会发现自己遇到麻烦。
无论如何...如果您执行以下操作,您会很快发现:
public MainClass(){
super();
synchronized(MainClass.class){
if(instance != null) throw new UnsupportedOperationException(
getClass()+" is singleton but constructor called more than once");
instance = this;
}
}
NetBeans 的编译器(如果您正在使用它)会提示“this
泄漏”,但这将保证您不会多次运行构造函数完成。
关于java - 如何在 JavaFX 中创建单例 MainClass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13943654/