我用Java编写了一个最小的可行html查看器。我面临的唯一问题是将浏览器组件的大小绑定到JFrame的大小。我知道我可能只错过了一行代码,但是今天我的google fu太弱了。有关浏览器的完整代码,请参见下文。目前,无论帧的大小如何,浏览器似乎都固定在300像素左右。
谢谢, 劳里
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javax.swing.*;
public class testBrowser {
/* Start swing thread */
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
showBrowser("http://www.stackoverflow.com");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void showBrowser(final String url) {
// This method is invoked on Swing thread
JFrame frame = new JFrame("FX");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
frame.setVisible(true);
frame.pack();
Platform.runLater(new Runnable() { // this will run initFX as JavaFX-Thread
@Override
public void run() {
initFX(fxPanel, url);
}
});
}
/* Creates a WebView and fires up google.com */
private static void initFX(final JFXPanel fxPanel, String url) {
Group group = new Group();
final Scene scene = new Scene(group);
WebView webView = new WebView();
group.getChildren().add(webView);
// Obtain the webEngine to navigate
WebEngine webEngine = webView.getEngine();
webEngine.load(url);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
fxPanel.setScene(scene);
}
});
}
}
答案 0 :(得分:3)
使用AnchorPane
创建场景,WebView
将绑定到AnchorPane
的所有4个角,并重新调整大小应使其适当拉伸
//Create Layout + WebView
AnchorPane anchorPane = new AnchorPane();
WebView webView = new WebView();
//Set Layout Constraint
AnchorPane.setTopAnchor(webView, 0.0);
AnchorPane.setBottomAnchor(webView, 0.0);
AnchorPane.setLeftAnchor(webView, 0.0);
AnchorPane.setRightAnchor(webView, 0.0);
//Add WebView to AnchorPane
anchorPane.getChildren().add(webView);
//Create Scene
final Scene scene = new Scene(anchorPane);
// Obtain the webEngine to navigate
WebEngine webEngine = webView.getEngine();
webEngine.load(url);