为了在我的 Swing 应用程序中支持 oAuth 2,我需要加载 Google 提供的网页 URL。由于JavaFX有更好的Web支持,我决定使用http://docs.oracle.com/javafx/2/swing/SimpleSwingBrowser.java.htm中的源代码
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SimpleSwingBrowser browser = new SimpleSwingBrowser();
browser.setVisible(true);
browser.loadURL(googleUrl);
}
});
由于 Oracle 提供的代码示例没有“自动调整网页”功能,因此我将得到类似的显示
最接近的例子是http://java-no-makanaikata.blogspot.com/2012/10/javafx-webview-size-trick.html 。但是,该示例要求我们注入(inject)自定义 <div>
标记为WebView
的内容,这不是我愿意做的事情。我更喜欢 HTML 内容加载,全部由 `WebView 完成。
最佳答案
这对我有用:
import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class WebViewHeightTest extends Application {
@Override
public void start(Stage primaryStage) {
String initialURL = "http://stackoverflow.com/questions/23170817/javafx-simpleswingbrowser-auto-fit-web-page" ;
BorderPane root = new BorderPane();
TextField locationBar = new TextField(initialURL);
WebView webView = new WebView();
WebEngine engine = webView.getEngine();
locationBar.setOnAction(event -> engine.load(makeUrl(locationBar.getText())));
root.setTop(locationBar);
root.setCenter(webView);
// Get full width and height of page when it's loaded:
engine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
int width = (Integer) engine.executeScript("document.body.scrollWidth");
int height = (Integer) engine.executeScript("document.body.scrollHeight");
System.out.printf("[%d, %d]%n", width, height);
}
});
engine.load(initialURL);
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private String makeUrl(String text) {
if (text.contains("://")) {
return text ;
} else {
return "http://"+text ;
}
}
public static void main(String[] args) {
launch(args);
}
}
关于JavaFX SimpleSwingBrowser 自动调整网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23170817/