用于选择目录的JFileChooser使用以下方法初始化:

JFileChooser directoryChooser = new JFileChooser();
directoryChooser.setDialogTitle("Choose Directory");
directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
directoryChooser.setAcceptAllFileFilterUsed(false);


并使用以下命令打开:

directoryChooser.updateUI();
directoryChooser.showOpenDialog(null);
File selectedFile = directoryChooser.getSelectedFile();


哪个有效,我可以选择目录,但我不喜欢它的外观:

java - JFilechooser更改默认外观-LMLPHP

我希望它具有与DirectoryChooser中的JavaFx相同的外观,例如与Chrome&Firefox中的“打开/保存”对话框相同的外观。这也将使手动输入路径成为可能。

java - JFilechooser更改默认外观-LMLPHP

是否可以在不使用JavaFx的情况下实现我想要的功能,如果可以,如何更改外观?

最佳答案

更新资料

我注意到您编辑了问题,以包括“未使用JavaFx”文本。由于此答案使用的是JavaFX,并且您不希望使用该技术,因此可以忽略它。



当您声明“我希望它的外观与JavaFx中的DirectoryChooser相同”时,您也可以仅在Swing应用程序中使用JavaFX中的DirectoryChooser。

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.DirectoryChooser;

import javax.swing.*;
import java.io.File;

public class SwingWithJavaFXDirectoryChooser {
    private static void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // creating a new JFXPanel (even if we don't use it), will initialize the JavaFX toolkit.
        new JFXPanel();

        DirectoryChooser directoryChooser = new DirectoryChooser();

        JButton button = new JButton("Choose directory");
        button.addActionListener(e ->
            // runLater is called to create the directory chooser on the JavaFX application thread.
            Platform.runLater(() -> {
                File selectedDirectory = directoryChooser.showDialog(null);
                System.out.println(selectedDirectory);
            })
        );
        frame.getContentPane().add(button);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SwingWithJavaFXDirectoryChooser::createAndShowGUI);
    }
}

10-07 20:02
查看更多