如何在控制器类的javafx应用程序中交换屏幕? [英] How to swap screens in a javafx-application in the controller-class?
本文介绍了如何在控制器类的javafx应用程序中交换屏幕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿我在网上搜索了很长一段时间,但我找不到解决以下问题的方法:
Hey I searched the net for quite a while but I couldn't find a solution to the following problem:
在javafx中你有3个基本文件; controller-class,fxml文件和应用程序类。现在我想在控制器中做出反应点击按钮(效果非常好)并更改该点击的屏幕(你通常使用stage.setScreen()),但我没有参考舞台(你可以在应用程序类中找到。)
In javafx you got 3 basic files; the controller-class, the fxml file and the application class. Now I want to react in the controller to a button-click (which works perfectly fine) and change the screen on that click (which you normally do with stage.setScreen() ), but I have no reference to the stage (which you can find in the application class).
应用程序 - 样本:
public class JavaFXApplication4 extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* 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);
}
}
FXML-样本:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxapplication4.SampleController">
<children>
<Button id="button" fx:id="nextScreen" layoutX="126.0" layoutY="90.0" onAction="#handleButtonAction" text="Next Screen" />
<Label fx:id="label" layoutX="126.0" layoutY="120.0" minHeight="16.0" minWidth="69.0" />
</children>
</AnchorPane>
控制器 - 样本:
public class SampleController implements Initializable {
@FXML
private Label label;
@FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hello World!");
//Here I want to swap the screen!
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
我会感谢任何帮助。
推荐答案
@FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hello World!");
//Here I want to swap the screen!
Stage stageTheEventSourceNodeBelongs = (Stage) ((Node)event.getSource()).getScene().getWindow();
// OR
Stage stageTheLabelBelongs = (Stage) label.getScene().getWindow();
// these two of them return the same stage
// Swap screen
stage.setScene(new Scene(new Pane()));
}
这篇关于如何在控制器类的javafx应用程序中交换屏幕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文