目前我有一个显示简单WebView
的{{1}},此index.html
在WebView
中创建,并在FXMLDocument.fxml
中控制。
如果我在FXMLDocumentController.java
内有一个按钮,我该如何检索它或访问它以使它使用java做某事?有没有一种动作处理程序来做这些事情?
FXMLDocuement.fxml:
index.html
FXMLDocumentController.java:
<?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="510.0" prefWidth="794.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication1.FXMLDocumentController">
<children>
<Button fx:id="button" layoutY="471.0" onAction="#handleButtonAction" text="Click Me!" />
<Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
<WebView id="WebView1" fx:id="WebView1" layoutY="5.0" prefHeight="444.0" prefWidth="882.0" />
<Label id="lbl1" fx:id="lbl1" layoutX="88.0" layoutY="475.0" prefHeight="17.0" prefWidth="99.0" text="Label" />
</children>
</AnchorPane>
包含main的类:JavaFXApplication1.java:
package javafxapplication1;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.web.WebView;
public class FXMLDocumentController implements Initializable {
@FXML
private Label label;
@FXML
private WebView WebView1;
@FXML
private Label lbl1;
@FXML
private void handleButtonAction(ActionEvent event) throws MalformedURLException {
System.out.println("You clicked me!");
label.setText("Hello World!");
lbl1.setText("Bonjour");
WebView1.getEngine().load(new File("C:/Users/hadhe/Desktop/boots/index.html").toURI().toURL().toString());
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
答案 0 :(得分:2)
HTML文档位于WebEngine的document属性中,但它是在后台加载的,因此必须等待它加载:
WebView1.getEngine().documentProperty().addListener((o, old, doc) -> listenToButton(doc));
WebView1.getEngine().load(new File("C:/Users/hadhe/Desktop/boots/index.html").toURI().toURL().toString());
文档对象是常规XML文档,因此如果按钮具有id
属性,则可以轻松检索它:
private void listenToButton(Document doc) {
if (doc == null) {
return;
}
String id = "app-action-button";
Element button = doc.getElementById(id);
// ...
}
如果按钮没有ID,您可以使用XPath搜索它:
private void listenToButton(Document doc) {
if (doc == null) {
return;
}
XPath xpath = XPathFactory.newInstance().newXPath();
Element button = (Element)
xpath.evaluate("//input[type='button']", doc,
XPathConstants.NODE);
// ...
}
最后,您可以向按钮添加DOM事件侦听器,如WebEngine documentation中所述:
((EventTarget) button).addEventListener("click", e -> doSomeAction(), false);
答案 1 :(得分:-1)