TheDoctor
TheDoctor

Reputation: 2512

JFilechooser change default appearance

A JFileChooser used to select a directory is initialized using:

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

and opened using:

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

which works and i can select a directory but i don't like it's appearance:

enter image description here

I would like it to have the same appearance as the DirectoryChooser in JavaFx, which is also the same appearance for example as the open/save dialog in Chrome & Firefox. That would also make it possible to enter the path manually.

enter image description here

Is it possible to achieve what i want without using JavaFx and if so how can i change it's appearance?

Upvotes: 1

Views: 615

Answers (1)

jewelsea
jewelsea

Reputation: 159341

Update

I noticed that you edited your question to include the text "without using JavaFx". As this answer is using JavaFX, and you don't wish to use that technology, you can ignore it.


As you state "I would like it to have the same appearance as the DirectoryChooser in JavaFx", then you may as well just use the DirectoryChooser from JavaFX from within your Swing application.

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

Upvotes: 1

Related Questions