有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JFilechooser更改默认外观

用于选择目录的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();

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

enter image description here

我希望它与JavaFx中的DirectoryChooser具有相同的外观,例如与Chrome&;火狐。这样还可以手动输入路径

enter image description here

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


共 (1) 个答案

  1. # 1 楼答案

    更新

    我注意到你编辑了你的问题,加入了“不使用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);
        }
    }