【问题标题】:How to save FXML control states before they're discarded?如何在 FXML 控件状态被丢弃之前保存它们?
【发布时间】:2015-12-05 20:05:15
【问题描述】:

这是我的第一个 FXML 应用程序。以前我对 Swing 已经很熟悉了。我只是想从舞台上的控件中保存几个值,以便用户输入的值在运行时重新加载。 ReliableOneShotCloseHandler 是我 posted a while ago here 的 JavaFX 版本。然而,当 windowClosing 函数被调用时,控件似乎已经被处理掉了......?我在指示的行收到 NullPointerException:

package testfxmlloader;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.control.Label;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

/**
*
* @author maskedcoder
*/
public class FXMLDocumentController implements Initializable {

    @FXML
    private Label label;

    @FXML
    private AnchorPane apMain;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("You clicked me!");
        label.setText("Hello World!");
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        ReliableOneShotCloseHandler roscSaveSettings = new ReliableOneShotCloseHandler(apMain.getScene().getWindow(), new ReliableOneShotCloseHandler.CloseDuties() {

            @Override
            public boolean confirmClose(WindowEvent e) {
                return true;
            }

            @Override
            public void windowClosing(WindowEvent e) {
                saveSettings();
            }
        });
    }   

    public void saveSettings() {
        System.out.println("save setting: " + label.getText());  // gets NullPointerException because label is null.
    }

}

class ReliableOneShotCloseHandler {

    public interface CloseDuties {
        public boolean confirmClose(WindowEvent e);
        public void windowClosing(WindowEvent e);
    }

    private final CloseDuties closeDuties;
    private boolean windowClosingFired = false;
    private final EventHandler<WindowEvent> openEvent;
    private final EventHandler<WindowEvent> closeEvent;

    public ReliableOneShotCloseHandler(Window thisWindow, CloseDuties iniCloseDuties) {
        super();
        closeDuties = iniCloseDuties;
        openEvent = (WindowEvent event) -> {
            windowClosingFired = false;
        };
        closeEvent = (WindowEvent event) -> {
            if(!windowClosingFired) {
                if(closeDuties.confirmClose(event)) {
                    closeDuties.windowClosing(event);
                    windowClosingFired = true;
                }
                else
                    event.consume();
            }
        };

        thisWindow.setOnShowing(openEvent);
        thisWindow.setOnShown(openEvent);
        thisWindow.setOnCloseRequest(closeEvent);
        thisWindow.setOnHiding(closeEvent);
        thisWindow.setOnHidden(closeEvent);
    }
}

public class TestFXMLLoader extends Application {
    FXMLLoader fxmll;
    FXMLDocumentController fdc;

    @Override
    public void start(Stage stage) throws Exception {
        fdc = new FXMLDocumentController();
        fxmll = new FXMLLoader();
        fxmll.setBuilderFactory(new JavaFXBuilderFactory());
        Parent root = fxmll.load(getClass().getResource("FXMLDocument.fxml"));
        fxmll.setController(fdc);

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

    /**
    * @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" fx:id="apMain" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.40" fx:controller="testfxmlloader.FXMLDocumentController">
    <children>
        <Button fx:id="button" layoutX="126" layoutY="90" onAction="#handleButtonAction" text="Click Me!" />
        <Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
    </children>
</AnchorPane>

应该在获得关闭权限之前调用windowClosing 函数,因此所有控件都应该正常工作。上面的测试代码基于 NetBeans 的默认 JavaFXML 应用程序,只是添加了 ReliableOneShotCloseHandler 和伴随代码。我的逻辑有问题吗?有没有其他方法可以做到这一点?

更新:包含了一些不应该包含的代码行。它们已被删除。

【问题讨论】:

    标签: java fxml


    【解决方案1】:

    从架构的角度来看,这段代码相当混乱。一般来说,我会清楚地将控制器和应用程序类分开。因此,应用程序类只加载 FXML 文件,从中引用控制器类,然后将其分配给场景或更准确地说是舞台。因此,控制器类仅负责将来自您的控制元素的任何事件作为您的onCloseRequest-Event 进行管理。

    另一个问题可能是同时使用EventFilter 和EventHandler。如果您在舞台上使用EventFilter,则它的所有节点和舞台本身将永远不会被调用它们的EventHandler。

    因此,最简单的解决方案是,如果您直接在控制器类的舞台上添加EventHandler,您可以直接访问所有其他控件(例如您的标签)。

    Main.java

    public class Main extends Application {
    
    @Override
    public void start(Stage primaryStage) throws Exception{
        FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
        Parent root = (Parent) loader.load();
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    
        Controller controller = (Controller)loader.getController();
        controller.setStage(primaryStage);
    }
    
    
    public static void main(String[] args) {
        launch(args);
    }
    
    } 
    

    sample.fxml

    <AnchorPane fx:id="apMain" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
       <children>
          <Button fx:id="button" layoutX="39.0" layoutY="35.0" mnemonicParsing="false" onAction="#handleButtonAction" text="Button" AnchorPane.leftAnchor="10.0" AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0" />
          <Label fx:id="label" layoutX="52.0" layoutY="102.0" text="Label" AnchorPane.leftAnchor="10.0" AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="50.0" />
       </children>
    </AnchorPane>
    

    Controller.java

    public class Controller implements Initializable {
    
    @FXML
    public AnchorPane apMain;
    
    @FXML
    public Button button;
    
    @FXML
    public Label label;
    
    @Override
    public void initialize(URL location, ResourceBundle resources) {
    
    }
    
    public void handleButtonAction() {
        System.out.println("You clicked me!");
        label.setText("Hello World!");
    }
    
    public void setStage(Stage stage){
        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                System.out.println(label.getText());
            }
        });
    }
    
    }
    

    【讨论】:

    • LOL 我从没想过我的代码会被认为是一团糟!我认为您基本上是在说我不了解 FXML 机制,这是真的。我认为您还建议我应该处理 FXMLDocumentController 中的 onCloseRequest 内容,我刚刚编辑了代码以反映这些内容。我删除了那些不应该存在的addEventFilter 行;它们在原始代码中被注释掉了,我不确定它们是如何进入的。我为顶级 AnchorPane 添加了一个变量,但是当我尝试 AnchorPane.getScene().getWindow() 时,AnchorPane.getScene() 也是空的。
    • 问题是这个阶段还不存在。因此,您需要稍后将其单独传递给控制器​​类。欲了解更多信息,请参阅stackoverflow.com/questions/13246211/…。
    • 这对我来说很有意义,但 .getController() 总是返回 null,无论我把它放在你做的地方,在 stage.show() 之后或更早。在我的原始代码中,我尝试简单地 create 然后 set 控制器,但这只会让我回到原来的问题;即使在setStage 函数中使用setOnCloseRequest,在closeRequest 事件处理程序被触发时,label 仍然是null。
    • 那么,您的代码中也奇怪的是,您在应用程序类中设置了控制器,即使您已经在 FXML 文件中引用了它。但是,我建议您只需复制粘贴我的解决方案并尝试一下。
    • 刚刚有机会尝试您的代码。有用!我看不出与我最初拥有的东西有任何区别(甚至在这个问题之前)。但这是我可以使用的。谢谢!
    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2019-11-06
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多