我需要将Stage传递给Controller Class中的Filechooser。
为此我需要在我的MainDesignClass中设置一个Controller。
这里有什么问题:
@Override
public void start( Stage primaryStage) throws Exception{
FXMLLoader loader= new FXMLLoader(getClass().getResources("myfxml.fxml");
Parent root =(Parent)loader.load();
primaryStage = new Stage();
Controller myController=loader.getController();
myController.setStage(primaryStage);
primaryStage.setTitle("myapp");
primaryStage.getIcons().add(image);
primaryStage.setScene(new Scene(root,900,600));
primaryStage.show();
}
setStage标记为红色。但为什么?为什么找不到方法?如何在Controller.class中使用FileChooser?
答案 0 :(得分:0)
要使用Controller,您必须在父对象中的FXML文件中设置它
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="157.0" prefWidth="430.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controllers.Controller">
答案 1 :(得分:0)
好的,我解决了这个问题:
主要类
public class Main extends Application {
private static Stage primaryStage; // Declare static Stage, so it can also be accessed in the controller and if you walk through Files!
private void setPrimaryStage(Stage stage) {
Main.primaryStage = stage;
}
static public Stage getPrimaryStage() {
return Main.primaryStage;
}
@Override
public void start(Stage primaryStage) throws Exception{
setPrimaryStage(primaryStage); // **Set the Stage**
//get new instance of FXMLLoader
FXMLLoader loader= new FXMLLoader(getClass().getResources("myfxml.fxml");
Parent root =(Parent)loader.load();
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
}
instanceofmain.getPrimaryStage()
在控制器类
public class Controller {
private Main mymainclass; //you need an instance of the main class to open the stage on this very instance, as it is static you will be able to get it then.
public void onMouseClickAction(ActionEvent e) {
Stage s = mymainclass.getPrimaryStage();
// do not apply any close actions, as you want to stay on the same stage
FileChooser chooser= new Filechooser();
File defaultfile = chooser.showOpenDialog(s); // for directories the command is showDialog(s);
}
}
没有其他线程与我的具体问题相关。