【问题标题】:JavaFX embed JFileChooser using SwingNode and get selected fileJavaFX 使用 SwingNode 嵌入 JFileChooser 并获取所选文件
【发布时间】:2019-12-16 12:10:44
【问题描述】:

我已使用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 FX based FileChooser
  • 不幸的是,我使用的是用 Swing 编写的遗留库。这就是 JFileChooser 的来源,所以我必须使用它。
  • 为什么不使用fileChooser.getSelectedFile

标签: java swing javafx jfilechooser


【解决方案1】:

出于好奇,我做了一个小例子来做到这一点。

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 上会有一个响应,然后您必须管理如何处理它,检查取消或接受等,然后在平台线程上触发一个操作。

【讨论】:

  • 喜欢文件名:)
  • Bingo,这正是我想要的,谢谢。我不熟悉 Platform.runlater()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-10
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 2014-08-09
相关资源
最近更新 更多