JavaFX使用SwingNode嵌入JFileChooser并获取所选文件

问题描述 投票:0回答:1

我已使用SwingNode将JFileChooser集成到JavaFX应用程序中。该对话框显示并可用,但是我不确定如何从中获取所选文件。

感谢您的帮助。

@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();
}
java swing javafx jfilechooser
1个回答
0
投票

出于好奇,我举了一个小例子。

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);
    }
}

EDT上将有一个响应,然后您必须管理该响应的处理方式,检查是否已取消或接受等,然后在平台线程上触发操作。

© www.soinside.com 2019 - 2024. All rights reserved.