【问题标题】:Popup window Label is not getting loaded弹出窗口标签未加载
【发布时间】:2014-03-13 15:29:22
【问题描述】:

1.尝试在弹出窗口中显示异常消息。没有出现异常消息。

2.例如:当我单击按钮时,将加载一个弹出窗口(第二个 fxml 文件),并在标签中显示适当的异常消息

3.弹出窗口出现,但是标签没有加载(粗体--> ExceptionLabel.setText("请输入正确的文件路径"))它说空指针异常。

4.我不确定我错过了什么。在 FX:ID 和链接主控制器的第二个 fxml 文件中声明的相同。提前致谢。

 @FXML
 public Label ExceptionLabel;
 Stage PopupWindow = new Stage();

 public void Buttonhandle(ActionEvent event) throws IOException {
    try {

        if(ESBOutboundFile!=null && OutputFile!=null){
         String Output = SBlogpaser.Logpaser(ESBInboundFile,ESBOutboundFile,OutputFile);
        System.out.println(Output);
        }else{
        Window(PopupWindow);
        **ExceptionLabel.setText("Please enter Proper file path");**

        }
    } catch (Exception ex) {
        System.out.println(ex);
    }

}

public void Window(Stage Popup) throws Exception {
   this.Popup=Popup;
   final FXMLLoader fxmlLoader = new FXMLLoader();
    Parent root= fxmlLoader.load(getClass().getResource("POPUPWindow.fxml"));            
    Scene scene1 = new Scene(root);
    Popup.setScene(scene1);
    Popup.show();      
}

如果我将标签保留在“确定”句柄按钮中,它就会显示出来。

【问题讨论】:

    标签: javafx-2


    【解决方案1】:

    您希望从哪里实例化 ExceptionLabel

    假设您将 POPUPWindow.fxml 文件根目录的 fx:controller 属性指向当前类,它只会创建该类的新实例,并将值注入该实例。当前实例中的ExceptionLabel字段不会被初始化。

    您可以通过将 FXMLLoader 的控制器设置为当前对象来完成这项工作,如下所示:

    public void window(Stage popup) throws Exception {
       this.popup=popup; // why?
       final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("POPUPWindow.fxml"));
        fxmlLoader.setController(this);
        Parent root= fxmlLoader.load();            
        Scene scene1 = new Scene(root);
        popup.setScene(scene1);
        popup.show();      
    }
    

    然后从 POPUPWindow.fxml 中删除 fx:controller 属性。

    不过,这似乎是一个非常糟糕的主意,因为现在当前对象正在充当两个不同 FXML 文件的控制器。这充其量只会令人困惑,并且在相当合理的条件下会产生奇怪的结果。为弹出窗口编写一个不同的控制器类会更好:

    public class PopupController {
      private final String message ;
      @FXML
      private Label exceptionLabel ;
    
      public PopupController(String message) {
        this.message = message ;
      }
    
      public void initialize() {
        exceptionLabel.setText(message);
      }
    }
    

    然后使用上面的window(...)方法,但是用

    fxmlLoader.setController(new PopupController("Please enter Proper file path"));
    

    显然,如果您正在重用 window(..) 方法,您可能希望将消息作为参数传递给该方法。

    【讨论】:

    • 你使用了 PopupController 的方式,但 exceptionLabel 仍然为空?
    • 这次最好没有异常,但没有显示消息。代码正确调用 popupcontroller 但它没有传递给 public void initialize() 方法。如果手动调用它会为标签集抛出空指针异常文字
    • 你的初始化方法没有被调用?
    • 好吧,那么你没有正确设置。 Here 是一个完整的示例。
    猜你喜欢
    • 2012-01-17
    • 2013-05-12
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 2019-10-16
    • 2019-08-22
    • 2017-07-29
    • 1970-01-01
    相关资源
    最近更新 更多