JavaFX:在UI屏幕之间导航的最佳实践

9 java javafx stage scene fxml

我想将UI屏幕从更改login.fxmlhome.fxml.

我应该改变StageScene?我不确定哪种是最佳做法?另外,我可以在控制器中为处理程序使用lambda表达式吗?

Mor*_*ayS 13

首先,让我们从Stage.vs 开始吧.Scene问题:

众所周知,JavaFX层次结构基于:Stage- > Scene- > Nodes(等).

看这里:

在此输入图像描述

实际上,我认为一个经验法则是未来:

  • 如果您打算前往程序流程中的其他位置(例如,登录 - >配置文件) - 请更改Stage.

  • 如果您在同一环境中(第一次登录 - >多次错误尝试后登录) - 更改Scene.

至于lambdas:啊......如果你的当前Java/ JavaFX版本具有abillity - 没有理由不使用.有关Java 8中控制器处理程序的更多信息,请参阅这个很棒的教程.


del*_*onX 5

我使用这种方法来改变场景JavaFX

/**
 * Controller class for menuFrame.fxml
 */
public class MenuFrameControl implements Initializable {

    @FXML private Button sceneButton1;
    @FXML private Button sceneButton2;
    @FXML private Button sceneButton3;

   /**
     * Event handling method, loads new scene from .fxml file
     * according to clicked button and initialize all components.
     * @param event
     * @throws IOException
     */
    @FXML
    private void handleMenuButtonAction (ActionEvent event) throws IOException {
        Stage stage = null;
        Parent myNewScene = null;

        if (event.getSource() == sceneButton1){
            stage = (Stage) sceneButton1.getScene().getWindow();
            myNewScene = FXMLLoader.load(getClass().getResource("/mvc/view/scene1.fxml"));
        } else if (event.getSource() == sceneButton2){
            stage = (Stage) flightBtn.getScene().getWindow();
            myNewScene = FXMLLoader.load(getClass().getResource("/mvc/view/scene2.fxml"));
        } else if (event.getSource() == sceneButton3) {
            stage=(Stage) staffBtn.getScene().getWindow();
            myNewScene = FXMLLoader.load(getClass().getResource("/mvc/view/scene3.fxml"));
        }

        Scene scene = new Scene(myNewScene);
        stage.setScene(scene);
        stage.setTitle("My New Scene");
        stage.show();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) { }
Run Code Online (Sandbox Code Playgroud)

所以基本上当你点击按钮时,它会将实际显示的Stage对象保存到stage变量中。然后它将Scene.fxml 文件中的新对象加载到myNewScene变量中,然后将这个新加载的Scene对象放入您保存的Stage对象中。

使用此代码,您可以制作基本的三按钮菜单,其中每个按钮只需使用单个Stage对象即可切换到不同的场景。