问题
i'm working on a browser with JavaFX i want to load a web page in FXMLFile1
contains WebView
just by clicking on Button
in FXMLFile2
to show the page in FXMLFile1
i tried this code :
@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){ }
}
}
note this class tabfirst
is in the Button
in the FXMLFile2
and the two FXMLfiles are in the same controller.
so please can any body show me what's wrong with my code and thanks in advance!
回答1:
I don't think you are setting web1. I think that because the 2 FXML files are using the same controller (Edit: my bad, I misread/misunderstood) you are expecting that they are automatically sharing variables, which they do not !
When the FXMLLoader loads an FXML file it creates a new instance of the controller every time. So the controller instance from FXMLfile1 doesn't know about the controller instance of FXMLfile2 or any of its variables.
There are about 5 different ways of sharing information between controllers:
- The simplest is just using getters and setters between the two.
- Also fairly simple is to bind properties between the two.
- You could setup listeners and then notify them of changes.
- Use a messaging bus.
- Use injection.
Which one you use depends on various factors and requires more information as to what you are trying to accomplish ?
A basic outline of options 1 & 2 would look something like this:
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
来源:https://stackoverflow.com/questions/28349951/how-to-load-a-web-page-in-a-webview-by-clicking-on-a-button-in-other-stage