colmulhall
colmulhall

Reputation: 1726

JavaFX embed JFileChooser using SwingNode and get selected file

I have integrated a JFileChooser into a JavaFX application using a SwingNode. The dialog displays and is usable, but I am unsure about how to get the selected file from it.

Thanks for any help.

@FXML
public void openDialog(MouseEvent event) {
    SwingNode swingNode = new SwingNode();

    SwingUtilities.invokeLater(() -> {
        swingNode.setContent(fileChooser);
    });

    BorderPane pane = new BorderPane();
    pane.setCenter(swingNode);

    Stage stage = new Stage();

    Scene scene = new Scene(pane, 500, 500);
    stage.setScene(scene);
    stage.show();
}

Upvotes: 0

Views: 398

Answers (1)

matt
matt

Reputation: 12347

Out of curiosity I made a small example to do this.

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.embed.swing.SwingNode;

import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;

public class JunkFx extends Application {
    public void openDialog(MouseEvent event) {
        JFileChooser fileChooser = new JFileChooser("why");
        SwingNode swingNode = new SwingNode();

        SwingUtilities.invokeLater(() -> {
            swingNode.setContent(fileChooser);
        });

        BorderPane pane = new BorderPane();
        pane.setCenter(swingNode);

        Stage stage = new Stage();

        Scene scene = new Scene(pane, 500, 500);
        stage.setScene(scene);
        stage.show();

        fileChooser.addActionListener(evt->{
            System.out.println(evt.getActionCommand());
            System.out.println(fileChooser.getSelectedFile());
            Platform.runLater(stage::hide);
        });

    }


    @Override
    public void start(Stage stage) throws Exception {
        Button b = new Button("click");
        b.setOnMouseClicked(this::openDialog);
        Scene scene = new Scene(new StackPane(b), 640, 480);
        stage.setTitle("open a dialog");
        stage.setScene(scene);
        stage.show();

    }

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

There will be a response on the EDT, then you have to manage what to do with it, checking for cancelled or accepted etc. then fire an action onto the Platform thread.

Upvotes: 4

Related Questions