Make javafx scene stretch with container frame

Viewed 1647

I've whipped together a minimal viable html viewer with Java. The only problem that I'm facing is binding the size of the browser component to the size of the JFrame. I know I'm probably only missing a single line of code, but my google fu is too weak today. See below for full code of the browser. Currently, the browser seems to be fixed at around 300 pixels, regardless of the size of the frame.

Thanks, Lauri

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);
        }
    });
}
}
1 Answers
Related