gpt4 book ai didi

javafx-2 - 如何在 Controller 类中的 JavaFX 应用程序中交换屏幕?

转载 作者:行者123 更新时间:2023-12-01 23:13:21 26 4
gpt4 key购买 nike

如果一个JavaFX项目中有3个文件; FXML 文件、FXML Controller 和应用程序类; Controller 如何响应按钮单击(效果非常好)并更改该单击上的屏幕(通常使用 stage.setScreen() 完成)?我没有对阶段的引用(它被传递给应用程序类的 start(Stage))。

应用示例:

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>

Controller 示例:

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) {
// ...
}
}

最佳答案

@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-2 - 如何在 Controller 类中的 JavaFX 应用程序中交换屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58364338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com