这个问题可能被认为是这个问题的简单扩展我有一个带有标签和 WebView 的简单应用程序。WebView 包含一个小矩形,其 onclick 应调用 JavaFX 中的方法并更改标签的文本。
以下是我的 FXML 文件
<?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>
我的 FXMLController 类是
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);
}
}
连接器类是
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);
}
}
}
在上面的连接器类中,如何获取 FXMLController 类的处理程序以便可以访问 setLabelText。
从问题的答案中,我可以理解 FXMLDocumentController 可以作为参数传递,但是当我通过 javascript 回调访问控制器时,我不确定如何访问它。