提交 8a08d694 编写于 作者: M mrkam

7027694: /jfc/FileChooserDemo demo needs to be improved

Reviewed-by: rupashka
上级 a0226263
/* /*
* Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -29,13 +29,12 @@ ...@@ -29,13 +29,12 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
/*
*/
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import javax.swing.filechooser.FileSystemView; import javax.swing.filechooser.FileSystemView;
/** /**
* This is a simple example that uses the FileSystemView class. * This is a simple example that uses the FileSystemView class.
* You can provide a superclass of the FileSystemView class with your own functionality. * You can provide a superclass of the FileSystemView class with your own functionality.
...@@ -43,6 +42,7 @@ import javax.swing.filechooser.FileSystemView; ...@@ -43,6 +42,7 @@ import javax.swing.filechooser.FileSystemView;
* @author Pavel Porvatov * @author Pavel Porvatov
*/ */
public class ExampleFileSystemView extends FileSystemView { public class ExampleFileSystemView extends FileSystemView {
/** /**
* Creates a new folder with the default name "New folder". This method is invoked * Creates a new folder with the default name "New folder". This method is invoked
* when the user presses the "New folder" button. * when the user presses the "New folder" button.
...@@ -65,8 +65,9 @@ public class ExampleFileSystemView extends FileSystemView { ...@@ -65,8 +65,9 @@ public class ExampleFileSystemView extends FileSystemView {
* Returns a list which appears in a drop-down list of the FileChooser component. * Returns a list which appears in a drop-down list of the FileChooser component.
* In this implementation only the home directory is returned. * In this implementation only the home directory is returned.
*/ */
@Override
public File[] getRoots() { public File[] getRoots() {
return new File[]{getHomeDirectory()}; return new File[] { getHomeDirectory() };
} }
/** /**
...@@ -74,9 +75,11 @@ public class ExampleFileSystemView extends FileSystemView { ...@@ -74,9 +75,11 @@ public class ExampleFileSystemView extends FileSystemView {
* A string with all upper case letters is returned for a directory. * A string with all upper case letters is returned for a directory.
* A string with all lower case letters is returned for a file. * A string with all lower case letters is returned for a file.
*/ */
@Override
public String getSystemDisplayName(File f) { public String getSystemDisplayName(File f) {
String displayName = super.getSystemDisplayName(f); String displayName = super.getSystemDisplayName(f);
return f.isDirectory() ? displayName.toUpperCase() : displayName.toLowerCase(); return f.isDirectory() ? displayName.toUpperCase() : displayName.
toLowerCase();
} }
} }
/* /*
* Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -29,14 +29,13 @@ ...@@ -29,14 +29,13 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
/*
*/
import javax.swing.*; import javax.swing.*;
import javax.swing.filechooser.*; import javax.swing.filechooser.*;
import java.io.File; import java.io.File;
import java.util.Hashtable; import java.util.HashMap;
import java.util.Map;
/** /**
* A convenience implementation of the FileView interface that * A convenience implementation of the FileView interface that
...@@ -61,15 +60,19 @@ import java.util.Hashtable; ...@@ -61,15 +60,19 @@ import java.util.Hashtable;
* @author Jeff Dinkins * @author Jeff Dinkins
*/ */
public class ExampleFileView extends FileView { public class ExampleFileView extends FileView {
private final Hashtable<String, Icon> icons = new Hashtable<String, Icon>();
private final Hashtable<File, String> fileDescriptions = new Hashtable<File, String>(); private final Map<String, Icon> icons = new HashMap<String, Icon>();
private final Hashtable<String, String> typeDescriptions = new Hashtable<String, String>(); private final Map<File, String> fileDescriptions =
new HashMap<File, String>();
private final Map<String, String> typeDescriptions =
new HashMap<String, String>();
/** /**
* The name of the file. Do nothing special here. Let * The name of the file. Do nothing special here. Let
* the system file view handle this. * the system file view handle this.
* @see FileView#getName * @see FileView#getName
*/ */
@Override
public String getName(File f) { public String getName(File f) {
return null; return null;
} }
...@@ -86,6 +89,7 @@ public class ExampleFileView extends FileView { ...@@ -86,6 +89,7 @@ public class ExampleFileView extends FileView {
* *
* @see FileView#getDescription * @see FileView#getDescription
*/ */
@Override
public String getDescription(File f) { public String getDescription(File f) {
return fileDescriptions.get(f); return fileDescriptions.get(f);
} }
...@@ -112,6 +116,7 @@ public class ExampleFileView extends FileView { ...@@ -112,6 +116,7 @@ public class ExampleFileView extends FileView {
* *
* @see FileView#getTypeDescription * @see FileView#getTypeDescription
*/ */
@Override
public String getTypeDescription(File f) { public String getTypeDescription(File f) {
return typeDescriptions.get(getExtension(f)); return typeDescriptions.get(getExtension(f));
} }
...@@ -122,12 +127,12 @@ public class ExampleFileView extends FileView { ...@@ -122,12 +127,12 @@ public class ExampleFileView extends FileView {
*/ */
private String getExtension(File f) { private String getExtension(File f) {
String name = f.getName(); String name = f.getName();
if(name != null) { if (name != null) {
int extensionIndex = name.lastIndexOf('.'); int extensionIndex = name.lastIndexOf('.');
if(extensionIndex < 0) { if (extensionIndex < 0) {
return null; return null;
} }
return name.substring(extensionIndex+1).toLowerCase(); return name.substring(extensionIndex + 1).toLowerCase();
} }
return null; return null;
} }
...@@ -147,10 +152,11 @@ public class ExampleFileView extends FileView { ...@@ -147,10 +152,11 @@ public class ExampleFileView extends FileView {
* *
* @see FileView#getIcon * @see FileView#getIcon
*/ */
@Override
public Icon getIcon(File f) { public Icon getIcon(File f) {
Icon icon = null; Icon icon = null;
String extension = getExtension(f); String extension = getExtension(f);
if(extension != null) { if (extension != null) {
icon = icons.get(extension); icon = icons.get(extension);
} }
return icon; return icon;
...@@ -168,11 +174,11 @@ public class ExampleFileView extends FileView { ...@@ -168,11 +174,11 @@ public class ExampleFileView extends FileView {
* *
* @see FileView#isTraversable * @see FileView#isTraversable
*/ */
@Override
public Boolean isTraversable(File f) { public Boolean isTraversable(File f) {
// if (some_reason) { // if (some_reason) {
// return Boolean.FALSE; // return Boolean.FALSE;
// } // }
return null; // Use default from FileSystemView return null; // Use default from FileSystemView
} }
} }
/* /*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -29,34 +29,75 @@ ...@@ -29,34 +29,75 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
/*
*/
import javax.swing.*; import java.lang.reflect.InvocationTargetException;
import javax.swing.filechooser.*; import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.util.ArrayList;
import javax.swing.plaf.FileChooserUI; import javax.swing.plaf.FileChooserUI;
import javax.swing.plaf.basic.BasicFileChooserUI; import javax.swing.plaf.basic.BasicFileChooserUI;
import java.awt.*;
import java.io.File; import java.io.File;
import java.awt.event.*;
import java.beans.*;
import java.util.Vector;
import static javax.swing.JFileChooser.*; import static javax.swing.JFileChooser.*;
/** /**
* *
* A demo which makes extensive use of the file chooser. * A demo which makes extensive use of the file chooser.
* *
* @author Jeff Dinkins * @author Jeff Dinkins
*/ */
@SuppressWarnings("serial")
public class FileChooserDemo extends JPanel implements ActionListener { public class FileChooserDemo extends JPanel implements ActionListener {
public static final String NIMBUS_LAF_NAME = "Nimbus";
private static JFrame frame; private static JFrame frame;
private final List<SupportedLaF> supportedLaFs =
new ArrayList<SupportedLaF>();
private static SupportedLaF nimbusLaF;
private final Vector<SupportedLaF> supportedLaFs = new Vector();
private static class SupportedLaF { private static class SupportedLaF {
private final String name; private final String name;
private final LookAndFeel laf; private final LookAndFeel laf;
...@@ -65,18 +106,15 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -65,18 +106,15 @@ public class FileChooserDemo extends JPanel implements ActionListener {
this.laf = laf; this.laf = laf;
} }
@Override
public String toString() { public String toString() {
return name; return name;
} }
} }
private JButton showButton; private JButton showButton;
private JCheckBox showAllFilesFilterCheckBox; private JCheckBox showAllFilesFilterCheckBox;
private JCheckBox showImageFilesFilterCheckBox; private JCheckBox showImageFilesFilterCheckBox;
private JCheckBox showFullDescriptionCheckBox; private JCheckBox showFullDescriptionCheckBox;
private JCheckBox useFileViewCheckBox; private JCheckBox useFileViewCheckBox;
private JCheckBox useFileSystemViewCheckBox; private JCheckBox useFileSystemViewCheckBox;
private JCheckBox accessoryCheckBox; private JCheckBox accessoryCheckBox;
...@@ -84,46 +122,44 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -84,46 +122,44 @@ public class FileChooserDemo extends JPanel implements ActionListener {
private JCheckBox useEmbedInWizardCheckBox; private JCheckBox useEmbedInWizardCheckBox;
private JCheckBox useControlsCheckBox; private JCheckBox useControlsCheckBox;
private JCheckBox enableDragCheckBox; private JCheckBox enableDragCheckBox;
private JRadioButton singleSelectionRadioButton; private JRadioButton singleSelectionRadioButton;
private JRadioButton multiSelectionRadioButton; private JRadioButton multiSelectionRadioButton;
private JRadioButton openRadioButton; private JRadioButton openRadioButton;
private JRadioButton saveRadioButton; private JRadioButton saveRadioButton;
private JRadioButton customButton; private JRadioButton customButton;
private JComboBox lafComboBox; private JComboBox lafComboBox;
private JRadioButton justFilesRadioButton; private JRadioButton justFilesRadioButton;
private JRadioButton justDirectoriesRadioButton; private JRadioButton justDirectoriesRadioButton;
private JRadioButton bothFilesAndDirectoriesRadioButton; private JRadioButton bothFilesAndDirectoriesRadioButton;
private JTextField customField; private JTextField customField;
private final ExampleFileView fileView; private final ExampleFileView fileView;
private final ExampleFileSystemView fileSystemView; private final ExampleFileSystemView fileSystemView;
private final static Dimension hpad10 = new Dimension(10, 1);
private final static Dimension hpad10 = new Dimension(10,1); private final static Dimension vpad20 = new Dimension(1, 20);
private final static Dimension vpad20 = new Dimension(1,20);
private final static Dimension vpad7 = new Dimension(1, 7); private final static Dimension vpad7 = new Dimension(1, 7);
private final static Dimension vpad4 = new Dimension(1, 4); private final static Dimension vpad4 = new Dimension(1, 4);
private final static Insets insets = new Insets(5, 10, 0, 10); private final static Insets insets = new Insets(5, 10, 0, 10);
private final FilePreviewer previewer; private final FilePreviewer previewer;
private final JFileChooser chooser; private final JFileChooser chooser;
@SuppressWarnings("LeakingThisInConstructor")
public FileChooserDemo() { public FileChooserDemo() {
UIManager.LookAndFeelInfo[] installedLafs = UIManager.getInstalledLookAndFeels(); UIManager.LookAndFeelInfo[] installedLafs = UIManager.
getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo lafInfo : installedLafs) { for (UIManager.LookAndFeelInfo lafInfo : installedLafs) {
try { try {
Class lnfClass = Class.forName(lafInfo.getClassName()); Class<?> lnfClass = Class.forName(lafInfo.getClassName());
LookAndFeel laf = (LookAndFeel)(lnfClass.newInstance()); LookAndFeel laf = (LookAndFeel) (lnfClass.newInstance());
if (laf.isSupportedLookAndFeel()) { if (laf.isSupportedLookAndFeel()) {
String name = lafInfo.getName(); String name = lafInfo.getName();
supportedLaFs.add(new SupportedLaF(name, laf)); SupportedLaF supportedLaF = new SupportedLaF(name, laf);
supportedLaFs.add(supportedLaF);
if (NIMBUS_LAF_NAME.equals(name)) {
nimbusLaF = supportedLaF;
}
} }
} catch (Exception e) { // If ANYTHING weird happens, don't add it } catch (Exception ignored) {
// If ANYTHING weird happens, don't add this L&F
} }
} }
...@@ -134,8 +170,10 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -134,8 +170,10 @@ public class FileChooserDemo extends JPanel implements ActionListener {
// Create Custom FileView // Create Custom FileView
fileView = new ExampleFileView(); fileView = new ExampleFileView();
fileView.putIcon("jpg", new ImageIcon(getClass().getResource("/resources/images/jpgIcon.jpg"))); fileView.putIcon("jpg", new ImageIcon(getClass().getResource(
fileView.putIcon("gif", new ImageIcon(getClass().getResource("/resources/images/gifIcon.gif"))); "/resources/images/jpgIcon.jpg")));
fileView.putIcon("gif", new ImageIcon(getClass().getResource(
"/resources/images/gifIcon.gif")));
// Create Custom FileSystemView // Create Custom FileSystemView
fileSystemView = new ExampleFileSystemView(); fileSystemView = new ExampleFileSystemView();
...@@ -155,8 +193,11 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -155,8 +193,11 @@ public class FileChooserDemo extends JPanel implements ActionListener {
customButton.addActionListener(optionListener); customButton.addActionListener(optionListener);
customField = new JTextField(8) { customField = new JTextField(8) {
@Override
public Dimension getMaximumSize() { public Dimension getMaximumSize() {
return new Dimension(getPreferredSize().width, getPreferredSize().height); return new Dimension(getPreferredSize().width,
getPreferredSize().height);
} }
}; };
customField.setText("Doit"); customField.setText("Doit");
...@@ -220,7 +261,8 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -220,7 +261,8 @@ public class FileChooserDemo extends JPanel implements ActionListener {
group3.add(justDirectoriesRadioButton); group3.add(justDirectoriesRadioButton);
justDirectoriesRadioButton.addActionListener(optionListener); justDirectoriesRadioButton.addActionListener(optionListener);
bothFilesAndDirectoriesRadioButton = new JRadioButton("Select Files or Directories"); bothFilesAndDirectoriesRadioButton = new JRadioButton(
"Select Files or Directories");
group3.add(bothFilesAndDirectoriesRadioButton); group3.add(bothFilesAndDirectoriesRadioButton);
bothFilesAndDirectoriesRadioButton.addActionListener(optionListener); bothFilesAndDirectoriesRadioButton.addActionListener(optionListener);
...@@ -241,7 +283,8 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -241,7 +283,8 @@ public class FileChooserDemo extends JPanel implements ActionListener {
showButton.setMnemonic('s'); showButton.setMnemonic('s');
// Create laf combo box // Create laf combo box
lafComboBox = new JComboBox(supportedLaFs); lafComboBox = new JComboBox(supportedLaFs.toArray());
lafComboBox.setSelectedItem(nimbusLaF);
lafComboBox.setEditable(false); lafComboBox.setEditable(false);
lafComboBox.addActionListener(optionListener); lafComboBox.addActionListener(optionListener);
...@@ -317,7 +360,8 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -317,7 +360,8 @@ public class FileChooserDemo extends JPanel implements ActionListener {
// ************* File & Directory Options ***************** // ************* File & Directory Options *****************
// ******************************************************** // ********************************************************
JPanel control4 = new InsetPanel(insets); JPanel control4 = new InsetPanel(insets);
control4.setBorder(BorderFactory.createTitledBorder("File and Directory Options")); control4.setBorder(BorderFactory.createTitledBorder(
"File and Directory Options"));
control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS)); control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS));
control4.add(Box.createRigidArea(vpad20)); control4.add(Box.createRigidArea(vpad20));
control4.add(justFilesRadioButton); control4.add(justFilesRadioButton);
...@@ -379,7 +423,7 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -379,7 +423,7 @@ public class FileChooserDemo extends JPanel implements ActionListener {
// clear the preview from the previous display of the chooser // clear the preview from the previous display of the chooser
JComponent accessory = chooser.getAccessory(); JComponent accessory = chooser.getAccessory();
if (accessory != null) { if (accessory != null) {
((FilePreviewer)accessory).loadImage(null); ((FilePreviewer) accessory).loadImage(null);
} }
if (useEmbedInWizardCheckBox.isSelected()) { if (useEmbedInWizardCheckBox.isSelected()) {
...@@ -393,25 +437,28 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -393,25 +437,28 @@ public class FileChooserDemo extends JPanel implements ActionListener {
if (retval == APPROVE_OPTION) { if (retval == APPROVE_OPTION) {
JOptionPane.showMessageDialog(frame, getResultString()); JOptionPane.showMessageDialog(frame, getResultString());
} else if (retval == CANCEL_OPTION) { } else if (retval == CANCEL_OPTION) {
JOptionPane.showMessageDialog(frame, "User cancelled operation. No file was chosen."); JOptionPane.showMessageDialog(frame,
"User cancelled operation. No file was chosen.");
} else if (retval == ERROR_OPTION) { } else if (retval == ERROR_OPTION) {
JOptionPane.showMessageDialog(frame, "An error occured. No file was chosen."); JOptionPane.showMessageDialog(frame,
"An error occured. No file was chosen.");
} else { } else {
JOptionPane.showMessageDialog(frame, "Unknown operation occured."); JOptionPane.showMessageDialog(frame, "Unknown operation occured.");
} }
} }
private void resetFileFilters(boolean enableFilters, private void resetFileFilters(boolean enableFilters,
boolean showExtensionInDescription) { boolean showExtensionInDescription) {
chooser.resetChoosableFileFilters(); chooser.resetChoosableFileFilters();
if (enableFilters) { if (enableFilters) {
FileFilter jpgFilter = createFileFilter("JPEG Compressed Image Files", FileFilter jpgFilter = createFileFilter(
showExtensionInDescription, "jpg"); "JPEG Compressed Image Files",
showExtensionInDescription, "jpg");
FileFilter gifFilter = createFileFilter("GIF Image Files", FileFilter gifFilter = createFileFilter("GIF Image Files",
showExtensionInDescription, "gif"); showExtensionInDescription, "gif");
FileFilter bothFilter = createFileFilter("JPEG and GIF Image Files", FileFilter bothFilter = createFileFilter("JPEG and GIF Image Files",
showExtensionInDescription, "jpg", showExtensionInDescription, "jpg",
"gif"); "gif");
chooser.addChoosableFileFilter(bothFilter); chooser.addChoosableFileFilter(bothFilter);
chooser.addChoosableFileFilter(jpgFilter); chooser.addChoosableFileFilter(jpgFilter);
chooser.addChoosableFileFilter(gifFilter); chooser.addChoosableFileFilter(gifFilter);
...@@ -419,7 +466,7 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -419,7 +466,7 @@ public class FileChooserDemo extends JPanel implements ActionListener {
} }
private FileFilter createFileFilter(String description, private FileFilter createFileFilter(String description,
boolean showExtensionInDescription, String...extensions) { boolean showExtensionInDescription, String... extensions) {
if (showExtensionInDescription) { if (showExtensionInDescription) {
description = createFileNameFilterDescriptionFromExtensions( description = createFileNameFilterDescriptionFromExtensions(
description, extensions); description, extensions);
...@@ -429,8 +476,8 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -429,8 +476,8 @@ public class FileChooserDemo extends JPanel implements ActionListener {
private String createFileNameFilterDescriptionFromExtensions( private String createFileNameFilterDescriptionFromExtensions(
String description, String[] extensions) { String description, String[] extensions) {
String fullDescription = (description == null) ? String fullDescription = (description == null) ? "(" : description
"(" : description + " ("; + " (";
// build the description from the extension list // build the description from the extension list
fullDescription += "." + extensions[0]; fullDescription += "." + extensions[0];
for (int i = 1; i < extensions.length; i++) { for (int i = 1; i < extensions.length; i++) {
...@@ -441,12 +488,15 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -441,12 +488,15 @@ public class FileChooserDemo extends JPanel implements ActionListener {
return fullDescription; return fullDescription;
} }
private class WizardDialog extends JDialog implements ActionListener { private class WizardDialog extends JDialog implements ActionListener {
CardLayout cardLayout; CardLayout cardLayout;
JPanel cardPanel; JPanel cardPanel;
JLabel messageLabel; JLabel messageLabel;
JButton backButton, nextButton, closeButton; JButton backButton, nextButton, closeButton;
@SuppressWarnings("LeakingThisInConstructor")
WizardDialog(JFrame frame, boolean modal) { WizardDialog(JFrame frame, boolean modal) {
super(frame, "Embedded JFileChooser Demo", modal); super(frame, "Embedded JFileChooser Demo", modal);
...@@ -494,15 +544,16 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -494,15 +544,16 @@ public class FileChooserDemo extends JPanel implements ActionListener {
// Workaround for bug 4528663. This is necessary to // Workaround for bug 4528663. This is necessary to
// pick up the contents of the file chooser text field. // pick up the contents of the file chooser text field.
// This will trigger an APPROVE_SELECTION action. // This will trigger an APPROVE_SELECTION action.
((BasicFileChooserUI)ui).getApproveSelectionAction().actionPerformed(null); ((BasicFileChooserUI) ui).getApproveSelectionAction().
actionPerformed(null);
} else { } else {
next(); next();
} }
} else if (src == closeButton) { } else if (src == closeButton) {
close(); close();
} else if (cmd == APPROVE_SELECTION) { } else if (APPROVE_SELECTION.equals(cmd)) {
next(); next();
} else if (cmd == CANCEL_SELECTION) { } else if (CANCEL_SELECTION.equals(cmd)) {
close(); close();
} }
} }
...@@ -528,6 +579,7 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -528,6 +579,7 @@ public class FileChooserDemo extends JPanel implements ActionListener {
setVisible(false); setVisible(false);
} }
@Override
public void dispose() { public void dispose() {
chooser.removeActionListener(this); chooser.removeActionListener(this);
...@@ -542,13 +594,18 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -542,13 +594,18 @@ public class FileChooserDemo extends JPanel implements ActionListener {
private String getResultString() { private String getResultString() {
String resultString; String resultString;
String filter = chooser.getFileFilter().getDescription(); String filter;
if (chooser.getFileFilter() == null) {
filter = "";
} else {
filter = chooser.getFileFilter().getDescription();
}
String path = null; String path = null;
boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY); boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY);
boolean isMulti = chooser.isMultiSelectionEnabled(); boolean isMulti = chooser.isMultiSelectionEnabled();
if (isMulti) { if (isMulti) {
File [] files = chooser.getSelectedFiles(); File[] files = chooser.getSelectedFiles();
if (files != null && files.length > 0) { if (files != null && files.length > 0) {
path = ""; path = "";
for (File file : files) { for (File file : files) {
...@@ -565,11 +622,10 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -565,11 +622,10 @@ public class FileChooserDemo extends JPanel implements ActionListener {
path = path.replace(" ", "&nbsp;"); path = path.replace(" ", "&nbsp;");
filter = filter.replace(" ", "&nbsp;"); filter = filter.replace(" ", "&nbsp;");
resultString = resultString =
"<html>You chose " + (isMulti ? "these" : "this") + " " + "<html>You chose " + (isMulti ? "these" : "this") + " " + (isDirMode ? (isMulti
(isDirMode ? (isMulti ? "directories" : "directory") ? "directories" : "directory")
: (isMulti ? "files" : "file")) + : (isMulti ? "files" : "file")) + ": <code>" + path
": <code>" + path + + "</code><br><br>with filter: <br><code>" + filter;
"</code><br><br>with filter: <br><code>" + filter;
} else { } else {
resultString = "Nothing was chosen"; resultString = "Nothing was chosen";
} }
...@@ -577,15 +633,14 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -577,15 +633,14 @@ public class FileChooserDemo extends JPanel implements ActionListener {
} }
/** An ActionListener that listens to the radio buttons. */ /** An ActionListener that listens to the radio buttons. */
private class OptionListener implements ActionListener { private class OptionListener implements ActionListener {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
JComponent c = (JComponent) e.getSource(); JComponent c = (JComponent) e.getSource();
boolean selected = false; boolean selected = false;
if (c instanceof JToggleButton) { if (c instanceof JToggleButton) {
selected = ((JToggleButton)c).isSelected(); selected = ((JToggleButton) c).isSelected();
} }
if (c == openRadioButton) { if (c == openRadioButton) {
...@@ -612,7 +667,7 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -612,7 +667,7 @@ public class FileChooserDemo extends JPanel implements ActionListener {
chooser.setAcceptAllFileFilterUsed(selected); chooser.setAcceptAllFileFilterUsed(selected);
} else if (c == showImageFilesFilterCheckBox) { } else if (c == showImageFilesFilterCheckBox) {
resetFileFilters(selected, resetFileFilters(selected,
showFullDescriptionCheckBox.isSelected()); showFullDescriptionCheckBox.isSelected());
showFullDescriptionCheckBox.setEnabled(selected); showFullDescriptionCheckBox.setEnabled(selected);
} else if (c == setHiddenCheckBox) { } else if (c == setHiddenCheckBox) {
chooser.setFileHidingEnabled(!selected); chooser.setFileHidingEnabled(!selected);
...@@ -637,7 +692,7 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -637,7 +692,7 @@ public class FileChooserDemo extends JPanel implements ActionListener {
} }
} else if (c == showFullDescriptionCheckBox) { } else if (c == showFullDescriptionCheckBox) {
resetFileFilters(showImageFilesFilterCheckBox.isSelected(), resetFileFilters(showImageFilesFilterCheckBox.isSelected(),
selected); selected);
} else if (c == justFilesRadioButton) { } else if (c == justFilesRadioButton) {
chooser.setFileSelectionMode(FILES_ONLY); chooser.setFileSelectionMode(FILES_ONLY);
} else if (c == justDirectoriesRadioButton) { } else if (c == justDirectoriesRadioButton) {
...@@ -653,27 +708,33 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -653,27 +708,33 @@ public class FileChooserDemo extends JPanel implements ActionListener {
chooser.setMultiSelectionEnabled(true); chooser.setMultiSelectionEnabled(true);
} }
} else if (c == lafComboBox) { } else if (c == lafComboBox) {
SupportedLaF supportedLaF = ((SupportedLaF)lafComboBox.getSelectedItem()); SupportedLaF supportedLaF = ((SupportedLaF) lafComboBox.
getSelectedItem());
LookAndFeel laf = supportedLaF.laf; LookAndFeel laf = supportedLaF.laf;
try { try {
UIManager.setLookAndFeel(laf); UIManager.setLookAndFeel(laf);
SwingUtilities.updateComponentTreeUI(frame); SwingUtilities.updateComponentTreeUI(frame);
if(chooser != null) { if (chooser != null) {
SwingUtilities.updateComponentTreeUI(chooser); SwingUtilities.updateComponentTreeUI(chooser);
} }
frame.pack(); frame.pack();
} catch (UnsupportedLookAndFeelException exc) { } catch (UnsupportedLookAndFeelException exc) {
// This should not happen because we already checked // This should not happen because we already checked
((DefaultComboBoxModel)lafComboBox.getModel()).removeElement(supportedLaF); ((DefaultComboBoxModel) lafComboBox.getModel()).
removeElement(supportedLaF);
} }
} }
} }
} }
private class FilePreviewer extends JComponent implements PropertyChangeListener {
private class FilePreviewer extends JComponent implements
PropertyChangeListener {
ImageIcon thumbnail = null; ImageIcon thumbnail = null;
@SuppressWarnings("LeakingThisInConstructor")
public FilePreviewer(JFileChooser fc) { public FilePreviewer(JFileChooser fc) {
setPreferredSize(new Dimension(100, 50)); setPreferredSize(new Dimension(100, 50));
fc.addPropertyChangeListener(this); fc.addPropertyChangeListener(this);
...@@ -684,9 +745,10 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -684,9 +745,10 @@ public class FileChooserDemo extends JPanel implements ActionListener {
thumbnail = null; thumbnail = null;
} else { } else {
ImageIcon tmpIcon = new ImageIcon(f.getPath()); ImageIcon tmpIcon = new ImageIcon(f.getPath());
if(tmpIcon.getIconWidth() > 90) { if (tmpIcon.getIconWidth() > 90) {
thumbnail = new ImageIcon( thumbnail = new ImageIcon(
tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT)); tmpIcon.getImage().getScaledInstance(90, -1,
Image.SCALE_DEFAULT));
} else { } else {
thumbnail = tmpIcon; thumbnail = tmpIcon;
} }
...@@ -695,23 +757,24 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -695,23 +757,24 @@ public class FileChooserDemo extends JPanel implements ActionListener {
public void propertyChange(PropertyChangeEvent e) { public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName(); String prop = e.getPropertyName();
if (prop == SELECTED_FILE_CHANGED_PROPERTY) { if (SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
if(isShowing()) { if (isShowing()) {
loadImage((File) e.getNewValue()); loadImage((File) e.getNewValue());
repaint(); repaint();
} }
} }
} }
@Override
public void paint(Graphics g) { public void paint(Graphics g) {
if(thumbnail != null) { if (thumbnail != null) {
int x = getWidth()/2 - thumbnail.getIconWidth()/2; int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
int y = getHeight()/2 - thumbnail.getIconHeight()/2; int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;
if(y < 0) { if (y < 0) {
y = 0; y = 0;
} }
if(x < 5) { if (x < 5) {
x = 5; x = 5;
} }
thumbnail.paintIcon(this, g, x, y); thumbnail.paintIcon(this, g, x, y);
...@@ -720,46 +783,57 @@ public class FileChooserDemo extends JPanel implements ActionListener { ...@@ -720,46 +783,57 @@ public class FileChooserDemo extends JPanel implements ActionListener {
} }
public static void main(String s[]) { public static void main(String s[]) {
/* try {
NOTE: By default, the look and feel will be set to the SwingUtilities.invokeAndWait(new Runnable() {
Cross Platform Look and Feel (which is currently Metal).
The user may someday be able to override the default public void run() {
via a system property. If you as the developer want to /*
be sure that a particular L&F is set, you can do so * NOTE: By default, the look and feel will be set to the
by calling UIManager.setLookAndFeel(). For example, the * Cross Platform Look and Feel (which is currently Metal).
first code snippet below forcibly sets the UI to be the * The following code tries to set the Look and Feel to Nimbus.
System Look and Feel. The second code snippet forcibly * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html
sets the look and feel to the Cross Platform L&F. */
try {
Snippet 1: for (LookAndFeelInfo info : UIManager.
try { getInstalledLookAndFeels()) {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); if (NIMBUS_LAF_NAME.equals(info.getName())) {
} catch (Exception exc) { UIManager.setLookAndFeel(info.getClassName());
System.err.println("Error loading L&F: " + exc); break;
} }
}
Snippet 2: } catch (Exception ignored) {
try { }
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception exc) { FileChooserDemo panel = new FileChooserDemo();
System.err.println("Error loading L&F: " + exc);
} frame = new JFrame("FileChooserDemo");
*/ frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add("Center", panel);
FileChooserDemo panel = new FileChooserDemo(); frame.pack();
frame.setVisible(true);
frame = new JFrame("FileChooserDemo"); }
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); });
frame.getContentPane().add("Center", panel); } catch (InterruptedException ex) {
frame.pack(); Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE,
frame.setVisible(true); null,
ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE,
null,
ex);
}
} }
private static class InsetPanel extends JPanel { private static class InsetPanel extends JPanel {
Insets i; Insets i;
InsetPanel(Insets i) { InsetPanel(Insets i) {
this.i = i; this.i = i;
} }
@Override
public Insets getInsets() { public Insets getInsets() {
return i; return i;
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册