synthfilechooserui.java

来自「java jdk 1.4的源码」· Java 代码 · 共 1,003 行 · 第 1/2 页

JAVA
1,003
字号
				if (children[l].getName().equals(str)) {				    file = children[l];				    childIndex = l + 1;				    break;				}			    }			}			fList.add(file);		    } while (fileName.length() > 0);		    if (fList.size() > 0) {			selectedFiles = (File[])fList.toArray(new File[fList.size()]);		    }		    resetGlobFilter();		} else {		    selectedFile = fs.createFileObject(fileName);		    if(!selectedFile.isAbsolute()) {		       selectedFile = fs.getChild(dir, fileName);		    }		    // check for wildcard pattern		    FileFilter currentFilter = chooser.getFileFilter();		    if (!selectedFile.exists() && isGlobPattern(fileName)) {			if (globFilter == null) {			    globFilter = new GlobFilter();			}			globFilter.setPattern(fileName);			if (!(currentFilter instanceof GlobFilter)) {			    actualFileFilter = currentFilter;			}			chooser.setFileFilter(null);			chooser.setFileFilter(globFilter);			return;		    }		    resetGlobFilter();		    // Check for directory change action		    boolean isDir = (selectedFile != null && selectedFile.isDirectory());		    boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile));		    boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled();		    boolean isFileSelEnabled = chooser.isFileSelectionEnabled();		    if (isDir && isTrav && !isDirSelEnabled) {			chooser.setCurrentDirectory(selectedFile);			return;		    } else if ((isDir || !isFileSelEnabled)			       && (!isDir || !isDirSelEnabled)			       && (!isDirSelEnabled || selectedFile.exists())) {			selectedFile = null;		    }		}	    }	    if (selectedFiles != null || selectedFile != null) {		if (selectedFiles != null) {		    chooser.setSelectedFiles(selectedFiles);		} else if (chooser.isMultiSelectionEnabled()) {		    chooser.setSelectedFiles(new File[] { selectedFile });		} else {		    chooser.setSelectedFile(selectedFile);		}		chooser.approveSelection();	    } else {		if (chooser.isMultiSelectionEnabled()) { 		    chooser.setSelectedFiles(null);		} else {		    chooser.setSelectedFile(null);		}		chooser.cancelSelection();	    }	}    }    /**     * Responds to a File Name completion request (e.g. Tab)     */    protected class FileNameCompletionAction extends AbstractAction {	protected FileNameCompletionAction() {	    super("fileNameCompletion");	}	public void actionPerformed(ActionEvent e) {	    JFileChooser chooser = getFileChooser();	    String fileName = getFileName();	    if (fileName != null) {		// Remove whitespace from beginning and end of filename		fileName = fileName.trim();	    }	    resetGlobFilter();	    if (fileName == null || fileName.equals("") ||		(chooser.isMultiSelectionEnabled() && fileName.startsWith("\""))) {		return;	    }	    FileFilter currentFilter = chooser.getFileFilter();	    if (globFilter == null) {		globFilter = new GlobFilter();	    }	    globFilter.setPattern(fileName + "*");	    if (!(currentFilter instanceof GlobFilter)) {		actualFileFilter = currentFilter;	    }	    chooser.setFileFilter(null);	    chooser.setFileFilter(globFilter);	    fileNameCompletionString = fileName;	}    }    private String fileNameCompletionString;    private void updateFileNameCompletion() {	if (fileNameCompletionString != null) {	    if (fileNameCompletionString.equals(getFileName())) {		File[] files = (File[])getModel().getFiles().toArray(new File[0]);		String str = getCommonStartString(files);		if (str != null && str.startsWith(fileNameCompletionString)) {		    setFileName(str);		}		fileNameCompletionString = null;	    }	}    }    private String getCommonStartString(File[] files) {	String str = null;	String str2 = null;	int i = 0;    if (files.length == 0) {        return null;    }	while (true) {	    for (int f = 0; f < files.length; f++) {		String name = files[f].getName();		if (f == 0) {		    if (name.length() == i) {			return str;		    }		    str2 = name.substring(0, i+1);		}		if (!name.startsWith(str2)) {		    return str;		}	    }	    str = str2;	    i++;	}    }    private void resetGlobFilter() {	if (actualFileFilter != null) {	    JFileChooser chooser = getFileChooser();	    FileFilter currentFilter = chooser.getFileFilter();	    if (currentFilter != null && currentFilter.equals(globFilter)) {		chooser.setFileFilter(actualFileFilter);		chooser.removeChoosableFileFilter(globFilter);	    }	    actualFileFilter = null;	}    }    private static boolean isGlobPattern(String fileName) {	return ((File.separatorChar == '\\' && fileName.indexOf('*') >= 0)		|| (File.separatorChar == '/' && (fileName.indexOf('*') >= 0						  || fileName.indexOf('?') >= 0						  || fileName.indexOf('[') >= 0)));    }        /* A file filter which accepts file patterns containing     * the special wildcard '*' on windows, plus '?', and '[ ]' on Unix.     */    class GlobFilter extends FileFilter {	Pattern pattern;	String globPattern;	public void setPattern(String globPattern) {	    char[] gPat = globPattern.toCharArray();	    char[] rPat = new char[gPat.length * 2];	    boolean isWin32 = (File.separatorChar == '\\');	    boolean inBrackets = false;	    StringBuffer buf = new StringBuffer();	    int j = 0;	    this.globPattern = globPattern;	    if (isWin32) {		// On windows, a pattern ending with *.* is equal to ending with *		int len = gPat.length;		if (globPattern.endsWith("*.*")) {		    len -= 2;		}		for (int i = 0; i < len; i++) {		    if (gPat[i] == '*') {			rPat[j++] = '.';		    }		    rPat[j++] = gPat[i];		}	    } else {		for (int i = 0; i < gPat.length; i++) {		    switch(gPat[i]) {		      case '*':			if (!inBrackets) {			    rPat[j++] = '.';			}			rPat[j++] = '*';			break;		      case '?':			rPat[j++] = inBrackets ? '?' : '.';			break;		      case '[':			inBrackets = true;			rPat[j++] = gPat[i];			if (i < gPat.length - 1) {			    switch (gPat[i+1]) {			      case '!':			      case '^':				rPat[j++] = '^';				i++;				break;			      case ']':				rPat[j++] = gPat[++i];				break;			    }			}			break;		      case ']':			rPat[j++] = gPat[i];			inBrackets = false;			break;		      case '\\':			if (i == 0 && gPat.length > 1 && gPat[1] == '~') {			    rPat[j++] = gPat[++i];			} else {			    rPat[j++] = '\\';			    if (i < gPat.length - 1 && "*?[]".indexOf(gPat[i+1]) >= 0) {				rPat[j++] = gPat[++i];			    } else {				rPat[j++] = '\\';			    }			}			break;		      default:			//if ("+()|^$.{}<>".indexOf(gPat[i]) >= 0) {			if (!Character.isLetterOrDigit(gPat[i])) {			    rPat[j++] = '\\';			}			rPat[j++] = gPat[i];			break;		    }		}	    }	    this.pattern = Pattern.compile(new String(rPat, 0, j), Pattern.CASE_INSENSITIVE);	}	public boolean accept(File f) {	    if (f == null) {		return false;	    }	    if (f.isDirectory()) {		return true;	    }	    return pattern.matcher(f.getName()).matches();	}	public String getDescription() {	    return globPattern;	}    }    // *******************************************************    // ************ FileChooser UI PLAF methods **************    // *******************************************************    /**     * Returns the default accept all file filter     */    public FileFilter getAcceptAllFileFilter(JFileChooser fc) {	return acceptAllFileFilter;    }    /**     * Returns the title of this dialog     */    public String getDialogTitle(JFileChooser fc) {	String dialogTitle = fc.getDialogTitle();	if (dialogTitle != null) {	    return dialogTitle;	} else if (fc.getDialogType() == JFileChooser.OPEN_DIALOG) {	    return openDialogTitleText;	} else if (fc.getDialogType() == JFileChooser.SAVE_DIALOG) {	    return saveDialogTitleText;	} else {	    return getApproveButtonText(fc);	}    }    public int getApproveButtonMnemonic(JFileChooser fc) {	int mnemonic = fc.getApproveButtonMnemonic();	if (mnemonic > 0) {	    return mnemonic;	} else if (fc.getDialogType() == JFileChooser.OPEN_DIALOG) {	    return openButtonMnemonic;	} else if (fc.getDialogType() == JFileChooser.SAVE_DIALOG) {	    return saveButtonMnemonic;	} else {	    return mnemonic;	}    }    public String getApproveButtonText(JFileChooser fc) {	String buttonText = fc.getApproveButtonText();	if (buttonText != null) {	    return buttonText;	} else if (fc.getDialogType() == JFileChooser.OPEN_DIALOG) {	    return openButtonText;	} else if (fc.getDialogType() == JFileChooser.SAVE_DIALOG) {	    return saveButtonText;	} else {	    return null;	}    }    // *****************************    // ***** Directory Actions *****    // *****************************    public Action getNewFolderAction() {	return newFolderAction;    }    public Action getGoHomeAction() {	return goHomeAction;    }    public Action getChangeToParentDirectoryAction() {	return changeToParentDirectoryAction;    }    public Action getApproveSelectionAction() {	return approveSelectionAction;    }    public Action getCancelSelectionAction() {	return cancelSelectionAction;    }    /**     * Acts on the "home" key event or equivalent event.     */    protected class GoHomeAction extends AbstractAction {	protected GoHomeAction() {	    super("Go Home");	}	public void actionPerformed(ActionEvent e) {	    JFileChooser fc = getFileChooser();	    fc.setCurrentDirectory(fc.getFileSystemView().getHomeDirectory());	}    }    public Action getFileNameCompletionAction() {	return fileNameCompletionAction;    }    protected class ChangeToParentDirectoryAction extends AbstractAction {	protected ChangeToParentDirectoryAction() {	    super("Go Up");	}	public void actionPerformed(ActionEvent e) {	    Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();	    if (focusOwner == null || !(focusOwner instanceof javax.swing.text.JTextComponent)) {		getFileChooser().changeToParentDirectory();	    }	}    }    /**     * Responds to a cancel request.     */    protected class CancelSelectionAction extends AbstractAction {	public void actionPerformed(ActionEvent e) {	    getFileChooser().cancelSelection();	}    }    // *****************************************    // ***** default AcceptAll file filter *****    // *****************************************    protected class AcceptAllFileFilter extends FileFilter {	public AcceptAllFileFilter() {	}	public boolean accept(File f) {	    return true;	}	public String getDescription() {	    return UIManager.getString("FileChooser.acceptAllFileFilterText",                                       getFileChooser().getLocale());	}    }    /**     * Creates a new folder.     */    protected class NewFolderAction extends AbstractAction {	protected NewFolderAction() {	    super("New Folder");	}	public void actionPerformed(ActionEvent e) {	    JFileChooser fc = getFileChooser();	    File currentDirectory = fc.getCurrentDirectory();	    File newFolder = null;	    try {		newFolder = fc.getFileSystemView().createNewFolder(currentDirectory);		if (fc.isMultiSelectionEnabled()) {		    fc.setSelectedFiles(new File[] { newFolder });		} else {		    fc.setSelectedFile(newFolder);		}	    } catch (IOException exc) {		JOptionPane.showMessageDialog(		    fc,		    newFolderErrorText + newFolderErrorSeparator + exc,		    newFolderErrorText, JOptionPane.ERROR_MESSAGE);		return;	    } 	    fc.rescanCurrentDirectory();	}    }    protected JButton getApproveButton(JFileChooser fc) {	return approveButton;    }    protected JButton getCancelButton(JFileChooser fc) {	return cancelButton;    }    // ***********************    // * FileView operations *    // ***********************    protected class SynthFileView extends FileView {	public String getName(File f) {	    // Note: Returns display name rather than file name	    String fileName = null;	    if(f != null) {		fileName = getFileChooser().getFileSystemView().getSystemDisplayName(f);	    }	    return fileName;	}	public String getDescription(File f) {	    return f.getName();	}	public String getTypeDescription(File f) {	    String type = getFileChooser().getFileSystemView().getSystemTypeDescription(f);	    if (type == null) {		if (f.isDirectory()) {		    type = directoryDescriptionText;		} else {		    type = fileDescriptionText;		}	    }	    return type;	}	public Icon getIcon(File f) {	    return null;	}	public Boolean isHidden(File f) {	    String name = f.getName();	    if(name != null && name.charAt(0) == '.') {		return Boolean.TRUE;	    } else {		return Boolean.FALSE;	    }	}    }}

⌨️ 快捷键说明

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