How to display default system icon for files in JFileChooser?

前端 未结 2 678
余生分开走
余生分开走 2021-01-05 13:17

How to display default system icon for files in JFileChooser? i.e. the icons of the files in JFileChooser should be the same as the icons that app

2条回答
  •  梦谈多话
    2021-01-05 13:27

    The way shown by @JavaTechnical is one way. Here is another (easier) way. Set the GUI (or at least the file chooser) to the native PLAF. E.G.

    File chooser with native PLAF

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    
    public class FileChooserIcons {
    
        public static void main(String[] args) {
            Runnable r = new Runnable() {
    
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(
                                UIManager.getSystemLookAndFeelClassName());
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                    // the GUI as seen by the user (without frame)
                    JPanel gui = new JPanel(new BorderLayout());
                    gui.setBorder(new EmptyBorder(20, 30, 20, 30));
    
                    JButton browse = new JButton("Show File Chooser");
                    final JFrame f = new JFrame("File Chooser");
                    ActionListener showChooser = new ActionListener() {
    
                        JFileChooser jfc = new JFileChooser();
    
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            jfc.showOpenDialog(f);
                        }
                    };
                    browse.addActionListener(showChooser);
                    gui.add(browse);
    
                    f.add(gui);
                    // Ensures JVM closes after frame(s) closed and
                    // all non-daemon threads are finished
                    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    // See http://stackoverflow.com/a/7143398/418556 for demo.
                    f.setLocationByPlatform(true);
    
                    // ensures the frame is the minimum size it needs to be
                    // in order display the components within it
                    f.pack();
                    // should be done last, to avoid flickering, moving,
                    // resizing artifacts.
                    f.setVisible(true);
                }
            };
            // Swing GUIs should be created and updated on the EDT
            // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
            SwingUtilities.invokeLater(r);
        }
    }
    

    Of course, if you are feeling brave, you might create a custom file chooser starting with something like the File Browser GUI.

提交回复
热议问题