I'm trying to make a javafx WebView that expands to the surrounding JPanel. According to this thread: http://www.coderanch.com/t/634791/JavaFX/java/Resizing-HTMLEditor-JavaFX, there is a bug in the WebView where you need to call GridPane.setHgrow
and GridPane.setVgrow
on the WebView. I've peppered my code with those calls, but the WebView is still 600x800px.
Note that the Scene has a blue background, so you can see that the javafx stuff does fill the entire JPanel. But the WebView does not fill the javafx Group/Scene.
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
public class Main {
private void initAndShowGUI() {
// This method is invoked on the EDT thread
JFrame frame = new JFrame("Swing and JavaFX");
frame.setSize(1000, 1000);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout(0, 0));
frame.getContentPane().add(panel, BorderLayout.CENTER);
JButton button = new JButton("button");
panel.add(button, BorderLayout.CENTER);
final JFXPanel fxPanel = new JFXPanel();
panel.add(fxPanel, BorderLayout.CENTER);
Platform.runLater(new Runnable() {
@Override
public void run() {
initFX(fxPanel);
}
});
}
private WebView webView;
private void initFX(JFXPanel fxPanel) {
// This method is invoked on the JavaFX thread
Scene scene = createScene();
fxPanel.setScene(scene);
GridPane.setHgrow(webView, Priority.ALWAYS);
GridPane.setVgrow(webView, Priority.ALWAYS);
}
private Scene createScene() {
Group root = new Group();
Scene scene = new Scene(root, Color.ALICEBLUE);
webView = new WebView();
GridPane.setHgrow(webView, Priority.ALWAYS);
GridPane.setVgrow(webView, Priority.ALWAYS);
WebEngine webEngine = webView.getEngine();
webEngine.load("http://www.google.com");
root.getChildren().add(webView);
GridPane.setHgrow(webView, Priority.ALWAYS);
GridPane.setVgrow(webView, Priority.ALWAYS);
return scene;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Main().initAndShowGUI();
}
});
}
}
Actually, I think I got a solution based off http://docs.oracle.com/javafx/2/webview/WebViewSample.java.htm:
I think the trick is to subclass Region, so that you can layout the WebView where you want it manually.
One approach is to add the
WebView
to aStackPane
, which "will attempt to resize each child to fill its content area." I've given the enclosingJFXPanel
to an arbitrary preferred size of640 x 480
; resize the frame to see how theStackPane
reflows theWebView
content based on the defaultPos.CENTER
.