我正在通過javafx web engine.load(url)加載url。我的要求是在頁面加載時通過更改字體的來源來修改嵌入的HTML,以正確加載字體。我能夠獲取文檔對象並將其轉換爲字符串,並替換相應的部分,然後使用webengine.loadContent(string)加載HTML。但是,一旦頁面出現並點擊提交按鈕,什麼都不會發生。下面是我的代碼,使所有這一切都發生:在JavaFX2的loadContent之後提交按鈕不起作用
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
String htmlBody = null;
@Override
public void changed(ObservableValue<? extends Worker.State> observableValue, Worker.State prevState, Worker.State newState) {
//To change body of implemented methods use File | Settings | File Templates.
//String htmlBody = null;
int count = 0;
if (newState == Worker.State.SUCCEEDED) {
browser.requestFocus();
// Get the document object from Engine.
Document doc = webEngine.getDocument();
try {
// Use Transformer to convert the HTML Object from the document top String format.
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
StringWriter outWriter = new StringWriter();
transformer.transform(new DOMSource(doc),new StreamResult(outWriter));
StringBuffer sb = outWriter.getBuffer();
htmlBody = sb.toString();
// Replace the font-family attribute in the style section to the actual URL of the font being used.
htmlBody = htmlBody.replace("font-family: medium", "font-family: url(http://1.10.30.45:8080/fonts/Md.ttf)");
observableValue.removeListener(this);
// Load the new HTML string to the Engine.
webEngine.loadContent(htmlBody, "text/html");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
webEngine.load(url);
//add the web view to the scene
getChildren().add(browser);
如果我刪除下面兩行,我能夠點擊登錄按鈕,並移動到歡迎頁面。 observableValue.removeListener(this);
// Load the new HTML string to the Engine.
webEngine.loadContent(htmlBody, "text/html");
但是在這種情況下,實際字體會更改爲某些默認字體。
我以前用userStyleSheetLocation嘗試過,但無法覆蓋已應用的CSS到頁面。但是,當我使用jdk 8和最新版本的javaFX時,字體問題已經得到解決。 –