⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 filechooserdemo.java

📁 一个小公司要求给写的很简单的任务管理系统。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
	int retval = chooser.showDialog(frame, null);	if (retval == APPROVE_OPTION) {	    JOptionPane.showMessageDialog(frame, getResultString());	} else if (retval == CANCEL_OPTION) {	    JOptionPane.showMessageDialog(frame, "User cancelled operation. No file was chosen.");	} else if (retval == ERROR_OPTION) {	    JOptionPane.showMessageDialog(frame, "An error occured. No file was chosen.");	} else {	    JOptionPane.showMessageDialog(frame, "Unknown operation occured.");	}    }    private void resetFileFilters(boolean enableFilters,                                  boolean showExtensionInDescription) {        chooser.resetChoosableFileFilters();        if (enableFilters) {            jpgFilter = createFileFilter("JPEG Compressed Image Files",                                         showExtensionInDescription, "jpg");            gifFilter = createFileFilter("GIF Image Files",                                         showExtensionInDescription, "gif");            bothFilter = createFileFilter("JPEG and GIF Image Files",                                          showExtensionInDescription, "jpg",                                          "gif");            chooser.addChoosableFileFilter(bothFilter);            chooser.addChoosableFileFilter(jpgFilter);            chooser.addChoosableFileFilter(gifFilter);        }    }    private FileFilter createFileFilter(String description,            boolean showExtensionInDescription, String...extensions) {        if (showExtensionInDescription) {            description = createFileNameFilterDescriptionFromExtensions(                    description, extensions);        }        return new FileNameExtensionFilter(description, extensions);    }    private String createFileNameFilterDescriptionFromExtensions(            String description, String[] extensions) {        String fullDescription = (description == null) ?                "(" : description + " (";        // build the description from the extension list        fullDescription += "." + extensions[0];        for (int i = 1; i < extensions.length; i++) {            fullDescription += ", .";            fullDescription += extensions[i];        }        fullDescription += ")";        return fullDescription;    }    class WizardDialog extends JDialog implements ActionListener {	CardLayout cardLayout;	JPanel cardPanel;	JLabel messageLabel;	JButton backButton, nextButton, closeButton;	WizardDialog(JFrame frame, boolean modal) {	    super(frame, "Embedded JFileChooser Demo", modal);	    cardLayout = new CardLayout();	    cardPanel = new JPanel(cardLayout);	    getContentPane().add(cardPanel, BorderLayout.CENTER);	    messageLabel = new JLabel("", JLabel.CENTER);	    cardPanel.add(chooser, "fileChooser");	    cardPanel.add(messageLabel, "label");	    cardLayout.show(cardPanel, "fileChooser");	    chooser.addActionListener(this);	    JPanel buttonPanel = new JPanel();	    backButton = new JButton("< Back");	    nextButton = new JButton("Next >");	    closeButton = new JButton("Close");	    buttonPanel.add(backButton);	    buttonPanel.add(nextButton);	    buttonPanel.add(closeButton);	    getContentPane().add(buttonPanel, BorderLayout.SOUTH);	    backButton.setEnabled(false);	    getRootPane().setDefaultButton(nextButton);	    backButton.addActionListener(this);	    nextButton.addActionListener(this);	    closeButton.addActionListener(this);	    pack();	    setLocationRelativeTo(frame);	}	public void actionPerformed(ActionEvent evt) {	    Object src = evt.getSource();	    String cmd = evt.getActionCommand();	    if (src == backButton) {		back();	    } else if (src == nextButton) {		FileChooserUI ui = chooser.getUI();		if (ui instanceof BasicFileChooserUI) {		    // Workaround for bug 4528663. This is necessary to		    // pick up the contents of the file chooser text field.		    // This will trigger an APPROVE_SELECTION action.		    ((BasicFileChooserUI)ui).getApproveSelectionAction().actionPerformed(null);		} else {		    next();		}	    } else if (src == closeButton) {		close();	    } else if (cmd == APPROVE_SELECTION) {		next();	    } else if (cmd == CANCEL_SELECTION) {		close();	    }	}	private void back() {	    backButton.setEnabled(false);	    nextButton.setEnabled(true);	    cardLayout.show(cardPanel, "fileChooser");	    getRootPane().setDefaultButton(nextButton);	    chooser.requestFocus();	}	private void next() {	    backButton.setEnabled(true);	    nextButton.setEnabled(false);	    messageLabel.setText(getResultString());	    cardLayout.show(cardPanel, "label");	    getRootPane().setDefaultButton(closeButton);	    closeButton.requestFocus();	}	private void close() {	    setVisible(false);	}	public void dispose() {	    chooser.removeActionListener(this);	    	    // The chooser is hidden by CardLayout on remove	    // so fix it here	    cardPanel.remove(chooser);	    chooser.setVisible(true);	    super.dispose();	}    }    private String getResultString() {	String resultString = null;	String filter = chooser.getFileFilter().getDescription();	String path = null;	boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY);	boolean isMulti = chooser.isMultiSelectionEnabled();	if (isMulti) {	    File [] files = chooser.getSelectedFiles();	    if (files != null && files.length > 0) {		path = "";		for (int i = 0; i < files.length; i++) {		    path = path + "<br>" + files[i].getPath();		}	    }	} else {	    File file = chooser.getSelectedFile();	    if (file != null) {		path = "<br>" + file.getPath();	    }	}	if (path != null) {	    path = path.replace(" ", "&nbsp;");	    filter = filter.replace(" ", "&nbsp;");	    resultString =		"<html>You chose " + (isMulti ? "these" : "this") + " " +		(isDirMode ? (isMulti ? "directories" : "directory")			   : (isMulti ? "files" : "file")) +		": <code>" + path +		"</code><br><br>with filter: <br><code>" + filter;	} else {	    resultString = "Nothing was chosen";	}	return resultString;    }    /** An ActionListener that listens to the radio buttons. */    class OptionListener implements ActionListener {	public void actionPerformed(ActionEvent e) {	    JComponent c = (JComponent) e.getSource();	    boolean selected = false;	    if (c instanceof JToggleButton) {		selected = ((JToggleButton)c).isSelected();	    }	    if (c == openRadioButton) {		chooser.setDialogType(OPEN_DIALOG);		customField.setEnabled(false);		repaint();	    } else if (c == useEmbedInWizardCheckBox) {		useControlsCheckBox.setEnabled(!selected);		useControlsCheckBox.setSelected(!selected);		chooser.setControlButtonsAreShown(!selected);	    } else if (c == useControlsCheckBox) {		chooser.setControlButtonsAreShown(selected);            } else if (c == enableDragCheckBox) {                chooser.setDragEnabled(selected);	    } else if (c == saveRadioButton) {		chooser.setDialogType(SAVE_DIALOG);		customField.setEnabled(false);		repaint();	    } else if (c == customButton || c == customField) {		customField.setEnabled(true);		chooser.setDialogType(CUSTOM_DIALOG);				repaint();            } else if (c == showAllFilesFilterCheckBox) {                chooser.setAcceptAllFileFilterUsed(selected);            } else if (c == showImageFilesFilterCheckBox) {                resetFileFilters(selected,                                 showFullDescriptionCheckBox.isSelected());                showFullDescriptionCheckBox.setEnabled(selected);	    } else if (c == setHiddenCheckBox) {		chooser.setFileHidingEnabled(!selected);	    } else if (c == accessoryCheckBox) {		if (selected) {		    chooser.setAccessory(previewer);		} else {		    chooser.setAccessory(null);		}	    } else if (c == useFileViewCheckBox) {		if (selected) {		    chooser.setFileView(fileView);		} else {		    chooser.setFileView(null);		}	    } else if (c == showFullDescriptionCheckBox) {                resetFileFilters(showImageFilesFilterCheckBox.isSelected(),                                 selected);	    } else if (c == justFilesRadioButton) {		chooser.setFileSelectionMode(FILES_ONLY);	    } else if (c == justDirectoriesRadioButton) {		chooser.setFileSelectionMode(DIRECTORIES_ONLY);	    } else if (c == bothFilesAndDirectoriesRadioButton) {		chooser.setFileSelectionMode(FILES_AND_DIRECTORIES);	    } else if (c == singleSelectionRadioButton) {		if (selected) {		    chooser.setMultiSelectionEnabled(false);		} 	    } else if (c == multiSelectionRadioButton) {		if (selected) {		    chooser.setMultiSelectionEnabled(true);		} 	    } else if (c == lafComboBox) {		SupportedLaF supportedLaF = ((SupportedLaF)lafComboBox.getSelectedItem());		LookAndFeel laf = supportedLaF.laf;		try {		    UIManager.setLookAndFeel(laf);		    SwingUtilities.updateComponentTreeUI(frame);		    if(chooser != null) {			SwingUtilities.updateComponentTreeUI(chooser);		    }		    frame.pack();		} catch (UnsupportedLookAndFeelException exc) {		    // This should not happen because we already checked		    ((DefaultComboBoxModel)lafComboBox.getModel()).removeElement(supportedLaF);		}	    }	}    }    class FilePreviewer extends JComponent implements PropertyChangeListener {	ImageIcon thumbnail = null;	public FilePreviewer(JFileChooser fc) {	    setPreferredSize(new Dimension(100, 50));	    fc.addPropertyChangeListener(this);	}	public void loadImage(File f) {            if (f == null) {                thumbnail = null;            } else {		ImageIcon tmpIcon = new ImageIcon(f.getPath());		if(tmpIcon.getIconWidth() > 90) {		    thumbnail = new ImageIcon(			tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));		} else {		    thumbnail = tmpIcon;		}	    }	}	public void propertyChange(PropertyChangeEvent e) {	    String prop = e.getPropertyName();	    if (prop == SELECTED_FILE_CHANGED_PROPERTY) {		if(isShowing()) {                    loadImage((File) e.getNewValue());		    repaint();		}	    }	}	public void paint(Graphics g) {	    if(thumbnail != null) {		int x = getWidth()/2 - thumbnail.getIconWidth()/2;		int y = getHeight()/2 - thumbnail.getIconHeight()/2;		if(y < 0) {		    y = 0;		}		if(x < 5) {		    x = 5;		}		thumbnail.paintIcon(this, g, x, y);	    }	}    }    public static void main(String s[]) {	/*	   NOTE: By default, the look and feel will be set to the	   Cross Platform Look and Feel (which is currently Metal).	   The user may someday be able to override the default	   via a system property. If you as the developer want to	   be sure that a particular L&F is set, you can do so	   by calling UIManager.setLookAndFeel(). For example, the	   first code snippet below forcibly sets the UI to be the	   System Look and Feel. The second code snippet forcibly	   sets the look and feel to the Cross Platform L&F.	   Snippet 1:	   try {	      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());	   } catch (Exception exc) {	      System.err.println("Error loading L&F: " + exc);	   }	   Snippet 2:	   try {	      UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());	   } catch (Exception exc) {	      System.err.println("Error loading L&F: " + exc);	   }	*/	FileChooserDemo panel = new FileChooserDemo();	frame = new JFrame("FileChooserDemo");	frame.addWindowListener(new WindowAdapter() {	    public void windowClosing(WindowEvent e) {System.exit(0);}	});	frame.getContentPane().add("Center", panel);	frame.pack();	frame.setVisible(true);    }    class InsetPanel extends JPanel {	Insets i;	InsetPanel(Insets i) {	    this.i = i;	}	public Insets getInsets() {	    return i;	}    }    /**     * A utility function that layers on top of the LookAndFeel's     * isSupportedLookAndFeel() method. Returns true if the LookAndFeel     * is supported. Returns false if the LookAndFeel is not supported     * and/or if there is any kind of error checking if the LookAndFeel     * is supported.     *     * The L&F menu will use this method to detemine whether the various     * L&F options should be active or inactive.     *     */     protected boolean isAvailableLookAndFeel(String laf) {         try {              Class lnfClass = Class.forName(laf);             LookAndFeel newLAF = (LookAndFeel)(lnfClass.newInstance());             return newLAF.isSupportedLookAndFeel();         } catch (Exception e) { // If ANYTHING weird happens, return false             return false;         }     }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -