我认为这是一个非常愚蠢的问题,但我无法做到这一点。如果您使用 Java 制作了 FXML 模板项目,您会自动获得三个文件。XML 中的视图、控制器和 java 中的启动文件。我想在控制器类中使用场景,但我不知道如何引用来执行此操作。这是我的例子:
public class CatchTheScene extends Application {
private Scene scene;
private Parent root;
@Override
public void start(Stage stage) throws Exception {
root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
FXMLDocumentController controller = new FXMLDocumentController(this);
scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
/**
* @return the scene
*/
public Scene getScene() {
return scene;
}
/**
* @param scene the scene to set
*/
public void setScene(Scene scene) {
this.scene = scene;
}
}
公共类 FXMLDocumentController 实现 Initializable {
private CatchTheScene c;
@FXML
private Label label;
@FXML
private Button button;
@FXML
private AnchorPane root;
@FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hello World!");
}
public FXMLDocumentController(CatchTheScene c)
{
this.c = c;
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
c.getScene().addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
System.out.println("I am the scene and have been clicked");
}
});
}
}