Path: blob/master/src/demo/share/jfc/FileChooserDemo/FileChooserDemo.java
41149 views
/*1* Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.2*3* Redistribution and use in source and binary forms, with or without4* modification, are permitted provided that the following conditions5* are met:6*7* - Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9*10* - Redistributions in binary form must reproduce the above copyright11* notice, this list of conditions and the following disclaimer in the12* documentation and/or other materials provided with the distribution.13*14* - Neither the name of Oracle nor the names of its15* contributors may be used to endorse or promote products derived16* from this software without specific prior written permission.17*18* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS19* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,20* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR21* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR22* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,23* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,24* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29*/3031/*32* This source code is provided to illustrate the usage of a given feature33* or technique and has been deliberately simplified. Additional steps34* required for a production-quality application, such as security checks,35* input validation and proper error handling, might not be present in36* this sample code.37*/38394041import java.lang.reflect.InvocationTargetException;42import java.util.logging.Level;43import java.util.logging.Logger;44import javax.swing.UIManager.LookAndFeelInfo;45import java.awt.BorderLayout;46import java.awt.CardLayout;47import java.awt.Component;48import java.awt.Dimension;49import java.awt.Graphics;50import java.awt.Image;51import java.awt.Insets;52import java.awt.event.ActionEvent;53import java.awt.event.ActionListener;54import java.beans.PropertyChangeEvent;55import java.beans.PropertyChangeListener;56import java.util.List;57import javax.swing.BorderFactory;58import javax.swing.Box;59import javax.swing.BoxLayout;60import javax.swing.ButtonGroup;61import javax.swing.DefaultComboBoxModel;62import javax.swing.ImageIcon;63import javax.swing.JButton;64import javax.swing.JCheckBox;65import javax.swing.JComboBox;66import javax.swing.JComponent;67import javax.swing.JDialog;68import javax.swing.JFileChooser;69import javax.swing.JFrame;70import javax.swing.JLabel;71import javax.swing.JOptionPane;72import javax.swing.JPanel;73import javax.swing.JRadioButton;74import javax.swing.JTextField;75import javax.swing.JToggleButton;76import javax.swing.LookAndFeel;77import javax.swing.SwingUtilities;78import javax.swing.UIManager;79import javax.swing.UnsupportedLookAndFeelException;80import javax.swing.WindowConstants;81import javax.swing.filechooser.FileFilter;82import javax.swing.filechooser.FileNameExtensionFilter;83import javax.swing.filechooser.FileSystemView;84import java.util.ArrayList;85import javax.swing.plaf.FileChooserUI;86import javax.swing.plaf.basic.BasicFileChooserUI;87import java.io.File;88import static javax.swing.JFileChooser.*;899091/**92*93* A demo which makes extensive use of the file chooser.94*95* @author Jeff Dinkins96*/97@SuppressWarnings("serial")98public class FileChooserDemo extends JPanel implements ActionListener {99100public static final String NIMBUS_LAF_NAME = "Nimbus";101private static JFrame frame;102private final List<SupportedLaF> supportedLaFs =103new ArrayList<SupportedLaF>();104private static SupportedLaF nimbusLaF;105106107private static class SupportedLaF {108109private final String name;110private final LookAndFeel laf;111112SupportedLaF(String name, LookAndFeel laf) {113this.name = name;114this.laf = laf;115}116117@Override118public String toString() {119return name;120}121}122private JButton showButton;123private JCheckBox showAllFilesFilterCheckBox;124private JCheckBox showImageFilesFilterCheckBox;125private JCheckBox showFullDescriptionCheckBox;126private JCheckBox useFileViewCheckBox;127private JCheckBox useFileSystemViewCheckBox;128private JCheckBox accessoryCheckBox;129private JCheckBox setHiddenCheckBox;130private JCheckBox useEmbedInWizardCheckBox;131private JCheckBox useControlsCheckBox;132private JCheckBox enableDragCheckBox;133private JRadioButton singleSelectionRadioButton;134private JRadioButton multiSelectionRadioButton;135private JRadioButton openRadioButton;136private JRadioButton saveRadioButton;137private JRadioButton customButton;138private JComboBox<SupportedLaF> lafComboBox;139private JRadioButton justFilesRadioButton;140private JRadioButton justDirectoriesRadioButton;141private JRadioButton bothFilesAndDirectoriesRadioButton;142private JTextField customField;143private final ExampleFileView fileView;144private final ExampleFileSystemView fileSystemView;145private static final Dimension hpad10 = new Dimension(10, 1);146private static final Dimension vpad20 = new Dimension(1, 20);147private static final Dimension vpad7 = new Dimension(1, 7);148private static final Dimension vpad4 = new Dimension(1, 4);149private static final Insets insets = new Insets(5, 10, 0, 10);150private final FilePreviewer previewer;151private final JFileChooser chooser;152153@SuppressWarnings("LeakingThisInConstructor")154public FileChooserDemo() {155UIManager.LookAndFeelInfo[] installedLafs = UIManager.156getInstalledLookAndFeels();157for (UIManager.LookAndFeelInfo lafInfo : installedLafs) {158try {159Class<?> lnfClass = Class.forName(lafInfo.getClassName());160LookAndFeel laf = (LookAndFeel) (lnfClass.getDeclaredConstructor().newInstance());161if (laf.isSupportedLookAndFeel()) {162String name = lafInfo.getName();163SupportedLaF supportedLaF = new SupportedLaF(name, laf);164supportedLaFs.add(supportedLaF);165if (NIMBUS_LAF_NAME.equals(name)) {166nimbusLaF = supportedLaF;167}168}169} catch (Exception ignored) {170// If ANYTHING weird happens, don't add this L&F171}172}173174setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));175176chooser = new JFileChooser();177previewer = new FilePreviewer(chooser);178179// Create Custom FileView180fileView = new ExampleFileView();181fileView.putIcon("jpg", new ImageIcon(getClass().getResource(182"/resources/images/jpgIcon.jpg")));183fileView.putIcon("gif", new ImageIcon(getClass().getResource(184"/resources/images/gifIcon.gif")));185186// Create Custom FileSystemView187fileSystemView = new ExampleFileSystemView();188189// create a radio listener to listen to option changes190OptionListener optionListener = new OptionListener();191192// Create options193openRadioButton = new JRadioButton("Open");194openRadioButton.setSelected(true);195openRadioButton.addActionListener(optionListener);196197saveRadioButton = new JRadioButton("Save");198saveRadioButton.addActionListener(optionListener);199200customButton = new JRadioButton("Custom");201customButton.addActionListener(optionListener);202203customField = new JTextField(8) {204205@Override206public Dimension getMaximumSize() {207return new Dimension(getPreferredSize().width,208getPreferredSize().height);209}210};211customField.setText("Doit");212customField.setAlignmentY(JComponent.TOP_ALIGNMENT);213customField.setEnabled(false);214customField.addActionListener(optionListener);215216ButtonGroup group1 = new ButtonGroup();217group1.add(openRadioButton);218group1.add(saveRadioButton);219group1.add(customButton);220221// filter buttons222showAllFilesFilterCheckBox = new JCheckBox("Show \"All Files\" Filter");223showAllFilesFilterCheckBox.addActionListener(optionListener);224showAllFilesFilterCheckBox.setSelected(true);225226showImageFilesFilterCheckBox = new JCheckBox("Show JPG and GIF Filters");227showImageFilesFilterCheckBox.addActionListener(optionListener);228showImageFilesFilterCheckBox.setSelected(false);229230accessoryCheckBox = new JCheckBox("Show Preview");231accessoryCheckBox.addActionListener(optionListener);232accessoryCheckBox.setSelected(false);233234// more options235setHiddenCheckBox = new JCheckBox("Show Hidden Files");236setHiddenCheckBox.addActionListener(optionListener);237238showFullDescriptionCheckBox = new JCheckBox("With File Extensions");239showFullDescriptionCheckBox.addActionListener(optionListener);240showFullDescriptionCheckBox.setSelected(true);241showFullDescriptionCheckBox.setEnabled(false);242243useFileViewCheckBox = new JCheckBox("Use FileView");244useFileViewCheckBox.addActionListener(optionListener);245useFileViewCheckBox.setSelected(false);246247useFileSystemViewCheckBox = new JCheckBox("Use FileSystemView", false);248useFileSystemViewCheckBox.addActionListener(optionListener);249250useEmbedInWizardCheckBox = new JCheckBox("Embed in Wizard");251useEmbedInWizardCheckBox.addActionListener(optionListener);252useEmbedInWizardCheckBox.setSelected(false);253254useControlsCheckBox = new JCheckBox("Show Control Buttons");255useControlsCheckBox.addActionListener(optionListener);256useControlsCheckBox.setSelected(true);257258enableDragCheckBox = new JCheckBox("Enable Dragging");259enableDragCheckBox.addActionListener(optionListener);260261// File or Directory chooser options262ButtonGroup group3 = new ButtonGroup();263justFilesRadioButton = new JRadioButton("Just Select Files");264justFilesRadioButton.setSelected(true);265group3.add(justFilesRadioButton);266justFilesRadioButton.addActionListener(optionListener);267268justDirectoriesRadioButton = new JRadioButton("Just Select Directories");269group3.add(justDirectoriesRadioButton);270justDirectoriesRadioButton.addActionListener(optionListener);271272bothFilesAndDirectoriesRadioButton = new JRadioButton(273"Select Files or Directories");274group3.add(bothFilesAndDirectoriesRadioButton);275bothFilesAndDirectoriesRadioButton.addActionListener(optionListener);276277singleSelectionRadioButton = new JRadioButton("Single Selection", true);278singleSelectionRadioButton.addActionListener(optionListener);279280multiSelectionRadioButton = new JRadioButton("Multi Selection");281multiSelectionRadioButton.addActionListener(optionListener);282283ButtonGroup group4 = new ButtonGroup();284group4.add(singleSelectionRadioButton);285group4.add(multiSelectionRadioButton);286287288// Create show button289showButton = new JButton("Show FileChooser");290showButton.addActionListener(this);291showButton.setMnemonic('s');292293// Create laf combo box294lafComboBox = new JComboBox<>(supportedLaFs.toArray(new SupportedLaF[0]));295lafComboBox.setSelectedItem(nimbusLaF);296lafComboBox.setEditable(false);297lafComboBox.addActionListener(optionListener);298299// ********************************************************300// ******************** Dialog Type ***********************301// ********************************************************302JPanel control1 = new InsetPanel(insets);303control1.setBorder(BorderFactory.createTitledBorder("Dialog Type"));304305control1.setLayout(new BoxLayout(control1, BoxLayout.Y_AXIS));306control1.add(Box.createRigidArea(vpad20));307control1.add(openRadioButton);308control1.add(Box.createRigidArea(vpad7));309control1.add(saveRadioButton);310control1.add(Box.createRigidArea(vpad7));311control1.add(customButton);312control1.add(Box.createRigidArea(vpad4));313JPanel fieldWrapper = new JPanel();314fieldWrapper.setLayout(new BoxLayout(fieldWrapper, BoxLayout.X_AXIS));315fieldWrapper.setAlignmentX(Component.LEFT_ALIGNMENT);316fieldWrapper.add(Box.createRigidArea(hpad10));317fieldWrapper.add(Box.createRigidArea(hpad10));318fieldWrapper.add(customField);319control1.add(fieldWrapper);320control1.add(Box.createRigidArea(vpad20));321control1.add(Box.createGlue());322323// ********************************************************324// ***************** Filter Controls **********************325// ********************************************************326JPanel control2 = new InsetPanel(insets);327control2.setBorder(BorderFactory.createTitledBorder("Filter Controls"));328control2.setLayout(new BoxLayout(control2, BoxLayout.Y_AXIS));329control2.add(Box.createRigidArea(vpad20));330control2.add(showAllFilesFilterCheckBox);331control2.add(Box.createRigidArea(vpad7));332control2.add(showImageFilesFilterCheckBox);333control2.add(Box.createRigidArea(vpad4));334JPanel checkWrapper = new JPanel();335checkWrapper.setLayout(new BoxLayout(checkWrapper, BoxLayout.X_AXIS));336checkWrapper.setAlignmentX(Component.LEFT_ALIGNMENT);337checkWrapper.add(Box.createRigidArea(hpad10));338checkWrapper.add(Box.createRigidArea(hpad10));339checkWrapper.add(showFullDescriptionCheckBox);340control2.add(checkWrapper);341control2.add(Box.createRigidArea(vpad20));342control2.add(Box.createGlue());343344// ********************************************************345// ****************** Display Options *********************346// ********************************************************347JPanel control3 = new InsetPanel(insets);348control3.setBorder(BorderFactory.createTitledBorder("Display Options"));349control3.setLayout(new BoxLayout(control3, BoxLayout.Y_AXIS));350control3.add(Box.createRigidArea(vpad20));351control3.add(setHiddenCheckBox);352control3.add(Box.createRigidArea(vpad7));353control3.add(useFileViewCheckBox);354control3.add(Box.createRigidArea(vpad7));355control3.add(useFileSystemViewCheckBox);356control3.add(Box.createRigidArea(vpad7));357control3.add(accessoryCheckBox);358control3.add(Box.createRigidArea(vpad7));359control3.add(useEmbedInWizardCheckBox);360control3.add(Box.createRigidArea(vpad7));361control3.add(useControlsCheckBox);362control3.add(Box.createRigidArea(vpad7));363control3.add(enableDragCheckBox);364control3.add(Box.createRigidArea(vpad20));365control3.add(Box.createGlue());366367// ********************************************************368// ************* File & Directory Options *****************369// ********************************************************370JPanel control4 = new InsetPanel(insets);371control4.setBorder(BorderFactory.createTitledBorder(372"File and Directory Options"));373control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS));374control4.add(Box.createRigidArea(vpad20));375control4.add(justFilesRadioButton);376control4.add(Box.createRigidArea(vpad7));377control4.add(justDirectoriesRadioButton);378control4.add(Box.createRigidArea(vpad7));379control4.add(bothFilesAndDirectoriesRadioButton);380control4.add(Box.createRigidArea(vpad20));381control4.add(singleSelectionRadioButton);382control4.add(Box.createRigidArea(vpad7));383control4.add(multiSelectionRadioButton);384control4.add(Box.createRigidArea(vpad20));385control4.add(Box.createGlue());386387388// ********************************************************389// **************** Look & Feel Switch ********************390// ********************************************************391JPanel panel = new JPanel();392panel.add(new JLabel("Look and Feel: "));393panel.add(lafComboBox);394panel.add(showButton);395396// ********************************************************397// ****************** Wrap 'em all up *********************398// ********************************************************399JPanel wrapper = new JPanel();400wrapper.setLayout(new BoxLayout(wrapper, BoxLayout.X_AXIS));401402add(Box.createRigidArea(vpad20));403404wrapper.add(Box.createRigidArea(hpad10));405wrapper.add(Box.createRigidArea(hpad10));406wrapper.add(control1);407wrapper.add(Box.createRigidArea(hpad10));408wrapper.add(control2);409wrapper.add(Box.createRigidArea(hpad10));410wrapper.add(control3);411wrapper.add(Box.createRigidArea(hpad10));412wrapper.add(control4);413wrapper.add(Box.createRigidArea(hpad10));414wrapper.add(Box.createRigidArea(hpad10));415416add(wrapper);417add(Box.createRigidArea(vpad20));418add(panel);419add(Box.createRigidArea(vpad20));420}421422public void actionPerformed(ActionEvent e) {423if (customButton.isSelected()) {424chooser.setApproveButtonText(customField.getText());425}426if (chooser.isMultiSelectionEnabled()) {427chooser.setSelectedFiles(null);428} else {429chooser.setSelectedFile(null);430}431// clear the preview from the previous display of the chooser432JComponent accessory = chooser.getAccessory();433if (accessory != null) {434((FilePreviewer) accessory).loadImage(null);435}436437if (useEmbedInWizardCheckBox.isSelected()) {438WizardDialog wizard = new WizardDialog(frame, true);439wizard.setVisible(true);440wizard.dispose();441return;442}443444int retval = chooser.showDialog(frame, null);445if (retval == APPROVE_OPTION) {446JOptionPane.showMessageDialog(frame, getResultString());447} else if (retval == CANCEL_OPTION) {448JOptionPane.showMessageDialog(frame,449"User cancelled operation. No file was chosen.");450} else if (retval == ERROR_OPTION) {451JOptionPane.showMessageDialog(frame,452"An error occurred. No file was chosen.");453} else {454JOptionPane.showMessageDialog(frame, "Unknown operation occurred.");455}456}457458private void resetFileFilters(boolean enableFilters,459boolean showExtensionInDescription) {460chooser.resetChoosableFileFilters();461if (enableFilters) {462FileFilter jpgFilter = createFileFilter(463"JPEG Compressed Image Files",464showExtensionInDescription, "jpg");465FileFilter gifFilter = createFileFilter("GIF Image Files",466showExtensionInDescription, "gif");467FileFilter bothFilter = createFileFilter("JPEG and GIF Image Files",468showExtensionInDescription, "jpg",469"gif");470chooser.addChoosableFileFilter(bothFilter);471chooser.addChoosableFileFilter(jpgFilter);472chooser.addChoosableFileFilter(gifFilter);473}474}475476private FileFilter createFileFilter(String description,477boolean showExtensionInDescription, String... extensions) {478if (showExtensionInDescription) {479description = createFileNameFilterDescriptionFromExtensions(480description, extensions);481}482return new FileNameExtensionFilter(description, extensions);483}484485private String createFileNameFilterDescriptionFromExtensions(486String description, String[] extensions) {487String fullDescription = (description == null) ? "(" : description488+ " (";489// build the description from the extension list490fullDescription += "." + extensions[0];491for (int i = 1; i < extensions.length; i++) {492fullDescription += ", .";493fullDescription += extensions[i];494}495fullDescription += ")";496return fullDescription;497}498499500private class WizardDialog extends JDialog implements ActionListener {501502CardLayout cardLayout;503JPanel cardPanel;504JLabel messageLabel;505JButton backButton, nextButton, closeButton;506507@SuppressWarnings("LeakingThisInConstructor")508WizardDialog(JFrame frame, boolean modal) {509super(frame, "Embedded JFileChooser Demo", modal);510511cardLayout = new CardLayout();512cardPanel = new JPanel(cardLayout);513getContentPane().add(cardPanel, BorderLayout.CENTER);514515messageLabel = new JLabel("", JLabel.CENTER);516cardPanel.add(chooser, "fileChooser");517cardPanel.add(messageLabel, "label");518cardLayout.show(cardPanel, "fileChooser");519chooser.addActionListener(this);520521JPanel buttonPanel = new JPanel();522backButton = new JButton("< Back");523nextButton = new JButton("Next >");524closeButton = new JButton("Close");525526buttonPanel.add(backButton);527buttonPanel.add(nextButton);528buttonPanel.add(closeButton);529530getContentPane().add(buttonPanel, BorderLayout.SOUTH);531532backButton.setEnabled(false);533getRootPane().setDefaultButton(nextButton);534535backButton.addActionListener(this);536nextButton.addActionListener(this);537closeButton.addActionListener(this);538539pack();540setLocationRelativeTo(frame);541}542543public void actionPerformed(ActionEvent evt) {544Object src = evt.getSource();545String cmd = evt.getActionCommand();546547if (src == backButton) {548back();549} else if (src == nextButton) {550FileChooserUI ui = chooser.getUI();551if (ui instanceof BasicFileChooserUI) {552// Workaround for bug 4528663. This is necessary to553// pick up the contents of the file chooser text field.554// This will trigger an APPROVE_SELECTION action.555((BasicFileChooserUI) ui).getApproveSelectionAction().556actionPerformed(null);557} else {558next();559}560} else if (src == closeButton) {561close();562} else if (APPROVE_SELECTION.equals(cmd)) {563next();564} else if (CANCEL_SELECTION.equals(cmd)) {565close();566}567}568569private void back() {570backButton.setEnabled(false);571nextButton.setEnabled(true);572cardLayout.show(cardPanel, "fileChooser");573getRootPane().setDefaultButton(nextButton);574chooser.requestFocus();575}576577private void next() {578backButton.setEnabled(true);579nextButton.setEnabled(false);580messageLabel.setText(getResultString());581cardLayout.show(cardPanel, "label");582getRootPane().setDefaultButton(closeButton);583closeButton.requestFocus();584}585586private void close() {587setVisible(false);588}589590@Override591public void dispose() {592chooser.removeActionListener(this);593594// The chooser is hidden by CardLayout on remove595// so fix it here596cardPanel.remove(chooser);597chooser.setVisible(true);598599super.dispose();600}601}602603private String getResultString() {604String resultString;605String filter;606if (chooser.getFileFilter() == null) {607filter = "";608} else {609filter = chooser.getFileFilter().getDescription();610}611String path = null;612boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY);613boolean isMulti = chooser.isMultiSelectionEnabled();614615if (isMulti) {616File[] files = chooser.getSelectedFiles();617if (files != null && files.length > 0) {618path = "";619for (File file : files) {620path = path + "<br>" + file.getPath();621}622}623} else {624File file = chooser.getSelectedFile();625if (file != null) {626path = "<br>" + file.getPath();627}628}629if (path != null) {630path = path.replace(" ", " ");631filter = filter.replace(" ", " ");632resultString =633"<html>You chose " + (isMulti ? "these" : "this") + " " + (isDirMode ? (isMulti634? "directories" : "directory")635: (isMulti ? "files" : "file")) + ": <code>" + path636+ "</code><br><br>with filter: <br><code>" + filter;637} else {638resultString = "Nothing was chosen";639}640return resultString;641}642643644/** An ActionListener that listens to the radio buttons. */645private class OptionListener implements ActionListener {646647public void actionPerformed(ActionEvent e) {648JComponent c = (JComponent) e.getSource();649boolean selected = false;650if (c instanceof JToggleButton) {651selected = ((JToggleButton) c).isSelected();652}653654if (c == openRadioButton) {655chooser.setDialogType(OPEN_DIALOG);656customField.setEnabled(false);657repaint();658} else if (c == useEmbedInWizardCheckBox) {659useControlsCheckBox.setEnabled(!selected);660useControlsCheckBox.setSelected(!selected);661chooser.setControlButtonsAreShown(!selected);662} else if (c == useControlsCheckBox) {663chooser.setControlButtonsAreShown(selected);664} else if (c == enableDragCheckBox) {665chooser.setDragEnabled(selected);666} else if (c == saveRadioButton) {667chooser.setDialogType(SAVE_DIALOG);668customField.setEnabled(false);669repaint();670} else if (c == customButton || c == customField) {671customField.setEnabled(true);672chooser.setDialogType(CUSTOM_DIALOG);673repaint();674} else if (c == showAllFilesFilterCheckBox) {675chooser.setAcceptAllFileFilterUsed(selected);676} else if (c == showImageFilesFilterCheckBox) {677resetFileFilters(selected,678showFullDescriptionCheckBox.isSelected());679showFullDescriptionCheckBox.setEnabled(selected);680} else if (c == setHiddenCheckBox) {681chooser.setFileHidingEnabled(!selected);682} else if (c == accessoryCheckBox) {683if (selected) {684chooser.setAccessory(previewer);685} else {686chooser.setAccessory(null);687}688} else if (c == useFileViewCheckBox) {689if (selected) {690chooser.setFileView(fileView);691} else {692chooser.setFileView(null);693}694} else if (c == useFileSystemViewCheckBox) {695if (selected) {696chooser.setFileSystemView(fileSystemView);697} else {698// Restore default behaviour699chooser.setFileSystemView(FileSystemView.getFileSystemView());700}701} else if (c == showFullDescriptionCheckBox) {702resetFileFilters(showImageFilesFilterCheckBox.isSelected(),703selected);704} else if (c == justFilesRadioButton) {705chooser.setFileSelectionMode(FILES_ONLY);706} else if (c == justDirectoriesRadioButton) {707chooser.setFileSelectionMode(DIRECTORIES_ONLY);708} else if (c == bothFilesAndDirectoriesRadioButton) {709chooser.setFileSelectionMode(FILES_AND_DIRECTORIES);710} else if (c == singleSelectionRadioButton) {711if (selected) {712chooser.setMultiSelectionEnabled(false);713}714} else if (c == multiSelectionRadioButton) {715if (selected) {716chooser.setMultiSelectionEnabled(true);717}718} else if (c == lafComboBox) {719SupportedLaF supportedLaF = ((SupportedLaF) lafComboBox.720getSelectedItem());721LookAndFeel laf = supportedLaF.laf;722try {723UIManager.setLookAndFeel(laf);724SwingUtilities.updateComponentTreeUI(frame);725if (chooser != null) {726SwingUtilities.updateComponentTreeUI(chooser);727}728frame.pack();729} catch (UnsupportedLookAndFeelException exc) {730// This should not happen because we already checked731((DefaultComboBoxModel<?>) lafComboBox.getModel()).732removeElement(supportedLaF);733}734}735736}737}738739740private class FilePreviewer extends JComponent implements741PropertyChangeListener {742743ImageIcon thumbnail = null;744745@SuppressWarnings("LeakingThisInConstructor")746public FilePreviewer(JFileChooser fc) {747setPreferredSize(new Dimension(100, 50));748fc.addPropertyChangeListener(this);749}750751public void loadImage(File f) {752if (f == null) {753thumbnail = null;754} else {755ImageIcon tmpIcon = new ImageIcon(f.getPath());756if (tmpIcon.getIconWidth() > 90) {757thumbnail = new ImageIcon(758tmpIcon.getImage().getScaledInstance(90, -1,759Image.SCALE_DEFAULT));760} else {761thumbnail = tmpIcon;762}763}764}765766public void propertyChange(PropertyChangeEvent e) {767String prop = e.getPropertyName();768if (SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {769if (isShowing()) {770loadImage((File) e.getNewValue());771repaint();772}773}774}775776@Override777public void paint(Graphics g) {778if (thumbnail != null) {779int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;780int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;781if (y < 0) {782y = 0;783}784785if (x < 5) {786x = 5;787}788thumbnail.paintIcon(this, g, x, y);789}790}791}792793public static void main(String[] s) {794try {795SwingUtilities.invokeAndWait(new Runnable() {796797public void run() {798/*799* NOTE: By default, the look and feel will be set to the800* Cross Platform Look and Feel (which is currently Metal).801* The following code tries to set the Look and Feel to Nimbus.802* https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html803*/804try {805for (LookAndFeelInfo info : UIManager.806getInstalledLookAndFeels()) {807if (NIMBUS_LAF_NAME.equals(info.getName())) {808UIManager.setLookAndFeel(info.getClassName());809break;810}811}812} catch (Exception ignored) {813}814815FileChooserDemo panel = new FileChooserDemo();816817frame = new JFrame("FileChooserDemo");818frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);819frame.getContentPane().add("Center", panel);820frame.pack();821frame.setVisible(true);822}823});824} catch (InterruptedException ex) {825Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE,826null,827ex);828} catch (InvocationTargetException ex) {829Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE,830null,831ex);832}833}834835836private static class InsetPanel extends JPanel {837838Insets i;839840InsetPanel(Insets i) {841this.i = i;842}843844@Override845public Insets getInsets() {846return i;847}848}849}850851852