JavaFX WebView grow to fill entire area

One approach is to add the WebView to a StackPane, which “will attempt to resize each child to fill its content area.” I’ve given the enclosing JFXPanel to an arbitrary preferred size of 640 x 480; resize the frame to see how the StackPane reflows the WebView content based on the default Pos.CENTER.

image

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

/** @see https://stackoverflow.com/a/31576647/230513 */
public class WebViewTest {

    private void initAndShowGUI() {
        // This method is invoked on the EDT thread
        JFrame frame = new JFrame("Swing and JavaFX");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JFXPanel fxPanel = new JFXPanel(){

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(640, 480);
            }
        };
        frame.add(fxPanel, BorderLayout.CENTER);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        Platform.runLater(() -> {
            initFX(fxPanel);
        });
    }

    private void initFX(JFXPanel fxPanel) {
        // This method is invoked on the JavaFX thread
        Scene scene = createScene();
        fxPanel.setScene(scene);
    }

    private Scene createScene() {
        StackPane root = new StackPane();
        Scene scene = new Scene(root);
        WebView  webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        webEngine.load("http://www.example.com");
        root.getChildren().add(webView);
        return scene;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new WebViewTest()::initAndShowGUI);
    }
}

Leave a Comment