0

I am having some difficulty understanding how to set up a pop up window that displays a web page in my Swing application. I have seen this code across multiple tutorials but what I am struggling with is how to include this in my own code.

Every tutorial uses the main method with this code, but I want to call this from one of my other classes and I am not sure how.

This is the code in question:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;



public class WebViewMain extends Application {

public static void main(String[] args) {
    Application.launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("WebView test");

    WebView  browser = new WebView();
    WebEngine engine = browser.getEngine();
    String url = "http://zoranpavlovic.blogspot.com/";
    engine.load(url);

    StackPane sp = new StackPane();
    sp.getChildren().add(browser);

    Scene root = new Scene(sp);

    primaryStage.setScene(root);
    primaryStage.show();
}
}

I want to be able to call the WebView from an ActionListener in one of my classes like this:

JButton mapExpandBtn = new JButton();
    mapExpandBtn.setText("Expand");
    mapExpandBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            new WebViewMain();
        }
    });

This doesn't work obviously. How can I adapt my own code or the WebViewMain code to get it to launch in my application?

user9109814
  • 175
  • 2
  • 14
  • I don't see you actually launching the JavaFX application in the `ActionListener`. What you're doing is simply creating a new instance of `WebViewMain` which does _not_ do any of the `Application.launch(...)` procedures (including calling `start(Stage)`). But what you're trying to do is use a `WebView` in a Swing application, right? You'll need to look at [javafx.embed.swing.JFXPanel](https://docs.oracle.com/javase/9/docs/api/javafx/embed/swing/JFXPanel.html). – Slaw Mar 25 '18 at 19:39
  • 1
    The `javafx.application.Application` class represents a JavaFX application (not a window), and specifically represents the lifecycle of the application (via methods like `init()`, `start()`, and `stop()`). Since you have an existing (swing) application, the `Application` class is not really relevant. I would also generally not recommend mixing Swing/AWT windows and JavaFX windows - so I think your best approach here is to open a new `JFrame` and use a [`JFXPanel`](https://docs.oracle.com/javase/9/docs/api/javafx/embed/swing/JFXPanel.html) to display the `WebView`. – James_D Mar 25 '18 at 19:53
  • Thank you both I managed to get it working. – user9109814 Mar 25 '18 at 21:50

0 Answers0