📄 fsatextfield.java
字号:
/*
* 08/09/2004
*
* FSATextField.java - A "File System-Aware" text field that keeps a drop-down
* list popuplated with files matching the text typed in by the user.
* Copyright (C) 2004 Robert Futrell
* email@address.com
* www.website.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.fife.ui;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FilenameFilter;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
/**
* A "File System-Aware" text field. When the user is typing into this text
* field, it automagically locates all files that begin with the text typed in,
* and populates a text field-style list with file choices. This is similar to
* the text field found in the "Run" dialog in Microsoft Windows.<p>
* When using this component, you MUST set the parent window (i.e., the
* window that contains this text field) so that the drop-down file menu
* properly disappears/resizes, etc. For example:<p>
* <code>
* public class MyDialog extends JDialog {
* ...
* public MyDialog() {
* FSATextField textField = new FSATextField();
* fsaTextField.discoverParentWindow();
* ...
* getContentPane().add(fsaTextField);
* </code></p>
* When possible, this component should be used over <code>FSAComboBox</code>
* as the combo box version isn't quite as flexible in allowing the user to
* choose values from its drop-down list, and it also flickers a lot when
* repainting.
*
* @author Robert Futrell
* @version 0.3
*/
public class FSATextField extends JTextField implements ComponentListener,
DocumentListener {
/**
*
*/
private static final long serialVersionUID = -10612015082528597L;
/**
* Whether or not the underlying OS is case-insensitive.
*/
private static final boolean IGNORE_CASE = FSATextField.getIgnoreCase();
/**
* File filter used if directories-only mode is set.
*/
private FilenameFilter directoriesOnlyFilenameFilter;
/**
* These are an attempt to speed things up in the "common" case. If the
* user types a letter into the text field but the last position of a
* file separator is the same as it was last time, then the "current
* directory" hasn't changed, so we can just keep the File instance for
* the directory we already have. We do this because doing a regex match
* loop through multiple file names can be slow on some systems.
*/
private int lastLastSeparator = -1;
private File directory;
private String dirName;
/**
* Variables used by the text field to implement the "combo-box"
* style list.
*/
private JList fileList;
private DefaultListModel fileListModel;
private JScrollPane scrollPane;
private JWindow popupWindow;
private boolean repopulatePopupList = true;
private boolean directoriesOnly;
private long lastCount = -1;
private boolean ignoreDocumentUpdates = false;
/**
* Cached values of the files in the current directory and the number
* of files in the current directory.
*/
private String[] containedFiles;
private int num;
/**
* The "current directory;" if the user is typing a relative pathname
* (i.e., not absolute), then assume this is the root directory.
*/
private String currentDirectory;
/**
* Whether or not the text field pops up a list of matching files.
*/
private boolean fileSystemAware;
private Window parent;
private JPanel contentPane;
/*****************************************************************************/
/**
* Creates a new FSATextField that previews both files and directories,
* and whose current directory is the program's current directory.
*/
public FSATextField() {
this(false, System.getProperty("user.dir"));
}
/*****************************************************************************/
/**
* Creates a new FSATextField.
*
* @param directoriesOnly Whether this text field should preview only
* directories (or both files and directories).
* @param currentDirectory The directory for which the text field should
* assume relative filenames are in.
*/
public FSATextField(boolean directoriesOnly, File currentDirectory) {
this(directoriesOnly, currentDirectory.getAbsolutePath());
}
/*****************************************************************************/
/**
* Creates a new FSATextField.
*
* @param directoriesOnly Whether this text field should preview only
* directories (or both files and directories).
* @param currentDirectory The directory for which the text field should
* assume relative filenames are in.
*/
public FSATextField(boolean directoriesOnly, String currentDirectory) {
super();
enableEvents(AWTEvent.FOCUS_EVENT_MASK);
setDirectoriesOnly(directoriesOnly);
fileListModel = new DefaultListModel();
fileList = new JList(fileListModel);
contentPane = new JPanel(new GridLayout(1,1));
scrollPane = new JScrollPane(fileList);
contentPane.add(scrollPane);
setCurrentDirectory(currentDirectory);
fileSystemAware = true;
}
/*****************************************************************************/
/**
* Adds an item to the file list.
*
* @param item The item to add to the file list.
* @see #removeAllItems
*/
public void addItem(String item) {
fileListModel.addElement(item);
}
/*****************************************************************************/
/**
* Called when the text component's document receives a style change.
* Since it is a plain document, this is never called.
*/
public void changedUpdate(DocumentEvent e) {
}
/*****************************************************************************/
/**
* Called when the parent dialog/frame of this text field is hidden.
* This should not be overridden.
*/
public void componentHidden(ComponentEvent e) {
processParentComponentEvent(e);
}
/*****************************************************************************/
/**
* Called when the parent dialog/frame of this text field is moved.
* This should not be overridden.
*/
public void componentMoved(ComponentEvent e) {
processParentComponentEvent(e);
}
/*****************************************************************************/
/**
* Called when the parent dialog/frame of this text field is resized.
* This should not be overridden.
*/
public void componentResized(ComponentEvent e) {
processParentComponentEvent(e);
}
/*****************************************************************************/
/**
* Called when the parent dialog/frame of this text field is shown.
* This should not be overridden.
*/
public void componentShown(ComponentEvent e) {
processParentComponentEvent(e);
}
/*****************************************************************************/
/**
* Sets the parent window of this text field (i.e., the window this text
* field is in). This needs to be set prior to the window being shown
* so that the file list can properly hide itself when necessary.<p>
*
* If you are adding this text field to a panel, and you're not yet sure
* who is the parent window, you can wrap this call in a
* <code>Runnable</code> and run it via
* <code>SwingUtilities.invokeLater()</code>.
*
* @return Whether a parent window was found. If you use this component
* correctly, this should always return <code>true</code>.
*/
public boolean discoverParentWindow() {
if (this.parent!=null)
parent.removeComponentListener(this);
Component parent = this.getParent();
while (parent!=null) {
if (parent instanceof Window) {
this.parent = (Window)parent;
this.parent.addComponentListener(this);
return true;
}
parent = parent.getParent();
}
return false;
}
/*****************************************************************************/
/**
* Returns the current directory for this text field.
*
* @return The current directory.
* @see #setCurrentDirectory
*/
public String getCurrentDirectory() {
return currentDirectory;
}
/*****************************************************************************/
/**
* Returns whether or not this text field is file-system-aware. If it is,
* then the drop-down list expands to display all matching files and
* directories as the user types.
*
* @return Whether or not this text field is file-system aware.
* @see #setFileSystemAware
*/
public boolean getFileSystemAware() {
return fileSystemAware;
}
/*****************************************************************************/
/**
* Returns whether or not the current OS is case-insensitive (e.g.,
* is Windows or OS X).
*
* @return Whether or not the underlying OS is case-insensitive.
*/
private static final boolean getIgnoreCase() {
String os = System.getProperty("os.name");
boolean ignoreCase = false;
if (os!=null) {
os = os.toLowerCase();
ignoreCase = os.indexOf("windows")>-1 ||
os.indexOf("mac os x")>-1;
}
return ignoreCase;
}
/*****************************************************************************/
/**
* Called when text is inserted into this text component.
*/
public void insertUpdate(DocumentEvent e) {
if (isShowing() && fileSystemAware && !ignoreDocumentUpdates)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateComboBoxContents();
}
});
}
/*****************************************************************************/
/**
* Installs key actions for scrolling through the file list. We make the
* up and down arrow keys scroll through the list, and the Enter key hide
* the popup window, if it exists, then call the root pane's action if it
* exists.
*/
private void installExtraKeyActions() {
InputMap inputMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "OnDown");
actionMap.put("OnDown", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (popupWindow!=null && popupWindow.isVisible()) {
int index = fileList.getSelectedIndex();
int size = fileList.getModel().getSize();
if (index<size-1) {
index++;
fileList.setSelectedIndex(index);
fileList.ensureIndexIsVisible(index);
ignoreDocumentUpdates = true;
setText((String)fileList.getSelectedValue());
ignoreDocumentUpdates = false;
}
}
}
});
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "OnUp");
actionMap.put("OnUp", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (popupWindow!=null && popupWindow.isVisible()) {
int index = fileList.getSelectedIndex();
if (index>0) {
index--;
fileList.setSelectedIndex(index);
fileList.ensureIndexIsVisible(index);
ignoreDocumentUpdates = true;
setText((String)fileList.getSelectedValue());
ignoreDocumentUpdates = false;
}
}
}
});
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0),
"OnPageDown");
actionMap.put("OnPageDown", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (popupWindow!=null && popupWindow.isVisible()) {
int index = fileList.getSelectedIndex();
int size = fileList.getModel().getSize();
if (index<size-1) {
int visRows = fileList.getVisibleRowCount();
index = Math.min(index+visRows, size-1);
fileList.setSelectedIndex(index);
fileList.ensureIndexIsVisible(index);
ignoreDocumentUpdates = true;
setText((String)fileList.getSelectedValue());
ignoreDocumentUpdates = false;
}
}
}
});
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0),
"OnPageUp");
actionMap.put("OnPageUp", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (popupWindow!=null && popupWindow.isVisible()) {
int index = fileList.getSelectedIndex();
int size = fileList.getModel().getSize();
if (index>0) {
int visRows = fileList.getVisibleRowCount();
index = Math.max(index-visRows, 0);
fileList.setSelectedIndex(index);
fileList.ensureIndexIsVisible(index);
ignoreDocumentUpdates = true;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -