This question might be considered as a simple extension to this qeustionI have a simple application with a label and a WebView. The WebView contains a small rectangle whose onclick should invoke a method in JavaFX and change the text of a label.
Following is my FXML file
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.web.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="webviewlabel.FXMLDocumentController">
<children>
<VBox prefHeight="200.0" prefWidth="100.0">
<children>
<Label id="lblSample" fx:id="lblSample" text="Sample Label" />
<WebView fx:id="wvSample" prefHeight="200.0" prefWidth="200.0" />
</children>
</VBox>
</children>
</AnchorPane>
And my FXMLController class is
public class FXMLDocumentController implements Initializable {
@FXML
private Label lblSample;
@FXML
private WebView wvSample;
private WebEngine webEngine ;
@FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// wvSample = new WebView();
initiateWeb();
}
public void initiateWeb() {
webEngine = wvSample.getEngine();
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<Worker.State>() {
public void changed(ObservableValue<? extends Worker.State> p, Worker.State oldState, Worker.State newState) {
if (newState == Worker.State.SUCCEEDED) {
JSObject win = (JSObject) webEngine.executeScript("window");
win.setMember("javaObj", new Connector());
System.out.println("FXMLDocumentController.initialize(): Called");
}
}
}
);
webEngine.loadContent(
"<div style='width: 50; height: 50; background: yellow;' onclick='javaObj.Connecting();' />"
);
}
public void setLabelText(String text)
{
System.out.println("FXMLDocumentController.setLabelText(): Called");
lblSample.setText(text);
}
}
And the Connector class is
public class Connector {
public void Connecting() {
try {
System.out.println("Connector.Connecting(): Called");
/*
FXMLLoader loader = new FXMLLoader(FXMLDocumentController.class.getResource("FXMLDocument.fxml"));
loader.load();
FXMLDocumentController controller = (FXMLDocumentController) loader.getController();
*/
// controller.setLabelText("Bye World");
} catch (Exception ex) {
Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
In the above connector class, how do I get the handler of FXMLController class so that the setLabelText could be accessed.
From the answers for the question, I could understand that the FXMLDocumentController could be passed as a parameter but I am not sure how to access the Controller when I am accessing it through javascript callback.