如何在fxml2中单击按钮以在JavaFX中的fxml1中加载网页?

时间:2015-02-10 13:10:19

标签: button webview javafx

我试图用JavaFX创建一个浏览器我想加载一个FXMLFile1包含WebView的网页,在FXMLfile2中有一个按钮,该按钮在WebView中加载一个网页,在FXMLFile1中我编写了这段代码但是不幸的是没有工作:

    @FXML
 public void tabfirst (ActionEvent ee) throws IOException { 


    try {

        FXMLLoader vve = new FXMLLoader(getClass().getResource("Choose.fxml"));
        Button b1 = tab1b = vve.getController();
         FXMLLoader vvve = new FXMLLoader(getClass().getResource("WorkSpace.fxml"));          
         WebView wv = web1 = vvve.getController();

        WebEngine myWebEngine = wv.getEngine();
        myWebEngine.load("https://www.google.com");
    }
   catch (IOException e){


   } 

}

请注意,此类tabfirst位于FXMLFile2的Button中,用于打开WebView中的网页,两个FXML文件使用相同的控制器。请回答我,谢谢!

1 个答案:

答案 0 :(得分:0)

您的选择控制器可能包含以下内容:

public class Choose
{
    @FXML private TextField  addressField;

    /** for Button in FXML onAction="#useAddress" */
    @FXML private void useAddress()
    {
        addressProp.set( addressField.getText() );
    }

    private final StringProperty  addressProp = new SimpleStringProperty();

    public StringProperty addressProperty()
    {
        return  addressProp;
    }
}

您的WorkSpace控制器可以:

public class WorkSpace
{
    @FXML private WebView  web;

    public void setAddress( String address )
    {
        web.getEngine().load( address );
    }
}

然后在加载两个FXML文件的控制器中,您将拥有类似的内容:

    FXMLLoader  workFxml = new FXMLLoader( getClass().getResource("WorkSpace.fxml") );
    Node  workView = workFxml.load(); // You must call load BEFORE getController !
    WorkSpace  workCtrl = workFxml.getController();

    FXMLLoader  chooseFxml = new FXMLLoader( getClass().getResource("Choose.fxml") );
    Node  chooseView = chooseFxml.load();
    Choose  chooseCtrl = chooseFxml.getController();

    chooseCtrl.addressProperty().addListener
    ( 
        (ov, old, newAddress) -> workCtrl.setAddress( newAddress ) 
    );

或者,如果您要从父FXML中加载两个FXML文件,例如:<fx:include fx:id="work" source="WorkSpace.fxml"/>,您将使用:

@FXML private WorkSpace  workController; // Must end with Controller !
@FXML private Choose  chooseController;

@FXML private void initialize()
{
    chooseController.addressProperty().addListener
    (
        (ov, old, newAddress) -> workController.setAddress( newAddress ) 
    );
}