如何通过单击其他阶段的按钮在 WebView 中加载网页?

How to load a web page in a WebView by clicking on a button in other stage?

我在使用 JavaFX 的浏览器上工作 我想在 FXMLFile1 中加载包含 WebView 的网页,只需单击 FXMLFile2 中的 Button 即可显示FXMLFile1 中的页面我试过这段代码:

@FXML
 public void tabfirst (ActionEvent ee) throws IOException { //for the FXMLFile2's button text.


            Socket socket = new Socket();
    try {

        //open cursor
        panoo.setCursor(Cursor.WAIT);
        que.setCursor(Cursor.WAIT);
        bbb.setCursor(Cursor.WAIT);

        //do work

        WebEngine myWebEngine = web1.getEngine(); //this web view is in FXMLFile1
        myWebEngine.load("https://www.google.com");



    }
   catch (IOException e){
       final  Stage stg = new Stage();           
        stg.initModality(Modality.APPLICATION_MODAL);
        stg.initOwner(stg);
        stg.setTitle("Cannot connect to the internet /n Please Verify your connection internet");
        labelno.setText("Cannot connect to the internet...");

       //set cursor
         ancpa.setCursor(Cursor.DEFAULT);

   } finally{
       try{ socket.close(); } catch (Exception e){ }
       }

}

注意这个 class tabfirstFXMLFile2 中的 Button 中,并且两个 FXML 文件在同一个控制器中。 所以请任何人告诉我我的代码有什么问题,在此先感谢!

我认为您没有设置 web1。我认为因为这 2 个 FXML 文件使用相同的控制器(编辑:我的错,我 misread/misunderstood)你期望它们自动共享变量,但它们没有!

当 FXMLLoader 加载 FXML 文件时,它每次都会创建一个 new 控制器实例。因此 FXMLfile1 的控制器实例不知道 FXMLfile2 的控制器实例或其任何变量。

控制器之间大约有 5 种不同的信息共享方式:

  1. 最简单的就是在两者之间使用 getter 和 setter。
  2. 在两者之间绑定属性也相当简单。
  3. 您可以设置侦听器,然后通知它们更改。
  4. 使用消息传递总线。
  5. 使用注入。

您使用哪一个取决于多种因素,并且需要有关您要完成的目标的更多信息?

选项 1 和 2 的基本轮廓如下所示:

FXMLLoader  fxml1 = .....
fxml1.load();
ctrl1 = fxml1.getController();

FXMLLoader  fxml2 = .....
fxml2.load();
ctrl2 = fxml2.getController();

ctrl2.set????( ctrl1.get????() );  // get something from the one and set it in the other
// if the value in ctrl1 changes it does not necessarily change in ctrl2

ctrl2.property????().bind( ctrl1.property???? );  // ctrl2 binds to a property in ctrl1
// if the value of the ctrl1 property changes it WILL also change in ctrl2