javafx-2 – 如何在controller-class中的javafx应用程序中交换屏幕?

前端之家收集整理的这篇文章主要介绍了javafx-2 – 如何在controller-class中的javafx应用程序中交换屏幕?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嘿,我搜索了一段时间,但我找不到解决以下问题的方法

javafx中有3个基本文件;控制器类,fxml文件和应用程序类.现在我想在控制器中做出一个按钮点击(其工作得很好)并更改该点击屏幕(通常使用stage.setScreen()),但我没有参考舞台(你可以在应用程序类中找到).

应用程序示例:

  1. public class JavaFXApplication4 extends Application {
  2.  
  3. @Override
  4. public void start(Stage stage) throws Exception {
  5. Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
  6.  
  7. Scene scene = new Scene(root);
  8.  
  9. stage.setScene(scene);
  10. stage.show();
  11. }
  12.  
  13. /**
  14. * The main() method is ignored in correctly deployed JavaFX application.
  15. * main() serves only as fallback in case the application can not be
  16. * launched through deployment artifacts,e.g.,in IDEs with limited FX
  17. * support. NetBeans ignores main().
  18. *
  19. * @param args the command line arguments
  20. */
  21. public static void main(String[] args) {
  22. launch(args);
  23. }
  24. }

FXML-样品:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <?import java.lang.*?>
  4. <?import java.util.*?>
  5. <?import javafx.scene.*?>
  6. <?import javafx.scene.control.*?>
  7. <?import javafx.scene.layout.*?>
  8.  
  9. <AnchorPane id="AnchorPane" prefHeight="200.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxapplication4.SampleController">
  10. <children>
  11. <Button id="button" fx:id="nextScreen" layoutX="126.0" layoutY="90.0" onAction="#handleButtonAction" text="Next Screen" />
  12. <Label fx:id="label" layoutX="126.0" layoutY="120.0" minHeight="16.0" minWidth="69.0" />
  13. </children>
  14. </AnchorPane>

控制器 – 示例:

  1. public class SampleController implements Initializable {
  2.  
  3. @FXML
  4. private Label label;
  5.  
  6. @FXML
  7. private void handleButtonAction(ActionEvent event) {
  8. System.out.println("You clicked me!");
  9. label.setText("Hello World!");
  10. //Here I want to swap the screen!
  11. }
  12.  
  13. @Override
  14. public void initialize(URL url,ResourceBundle rb) {
  15. // TODO
  16. }
  17. }

我会感谢任何一种帮助.

解决方法

  1. @FXML
  2. private void handleButtonAction(ActionEvent event) {
  3. System.out.println("You clicked me!");
  4. label.setText("Hello World!");
  5. //Here I want to swap the screen!
  6.  
  7. Stage stageTheEventSourceNodeBelongs = (Stage) ((Node)event.getSource()).getScene().getWindow();
  8. // OR
  9. Stage stageTheLabelBelongs = (Stage) label.getScene().getWindow();
  10. // these two of them return the same stage
  11. // Swap screen
  12. stage.setScene(new Scene(new Pane()));
  13. }

猜你在找的Java相关文章