jfilechooser.java
来自「纯java操作系统jnode,安装简单和操作简单的个人使用的Java操作系统」· Java 代码 · 共 876 行 · 第 1/2 页
JAVA
876 行
/** Implements the ActionListener interface. Handles button-presses,
* and the ENTER keystroke in the Pathname field.
*/
public void actionPerformed(ActionEvent e_) {
Object source = e_.getSource();
if (source == _parentButton) {
_doParentDirectoryAction();
}
else if (source == _newButton) {
_doNewDirectoryAction();
}
else if (source == _approveButton) {
_doApproveAction();
}
else if (source == _cancelButton) {
_doCancelAction();
}
else if (source == _locationField) {
_doApproveAction();
}
}
/** Implements the KeyListener interface
*/
public void keyPressed(KeyEvent e_) {
int key = e_.getKeyCode();
if (key == PARENT_DIRECTORY_ACCELERATOR) {
_doParentDirectoryAction();
}
else if (key == NEW_DIRECTORY_ACCELERATOR) {
_doNewDirectoryAction();
}
else if (key == APPROVE_ACCELERATOR) {
_doApproveAction();
}
else if (key == CANCEL_ACCELERATOR) {
_doCancelAction();
}
}
/** Implements the KeyListener interface
*/
public void keyTyped(KeyEvent e_) {
}
/** Implements KeyListener interface; is never called.
*/
public void keyReleased(KeyEvent e_) { }
/** Implements the ListSelectionListener interface.
*/
public void valueChanged(ListSelectionEvent e_) {
String listitem = (String) _dirList.getSelectedValue();
if (listitem == null) {
// The selection is empty; so there must have been a
// file selected, but it has just been deselected.
_locationField.setText(_currentDirectory.getAbsolutePath());
return;
}
/* Strip the trailing "/"
*/
if (listitem.endsWith("/"))
listitem = listitem.substring(0, listitem.length()-1);
File file = new File(_currentDirectory, listitem);
if (file.canRead() == false) {
String[] msgs = {
"File or directory not readable:",
file.getAbsolutePath() };
JOptionPane.showMessageDialog(
this, msgs, "Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (file.isDirectory() == false) {
if (_fileSelectionMode == DIRECTORIES_ONLY) {
String[] msgs = {
"Not a directory:",
file.getAbsolutePath() };
JOptionPane.showMessageDialog(
this, msgs, "Error", JOptionPane.ERROR_MESSAGE);
}
else {
_locationField.setText(file.getAbsolutePath());
}
return;
}
// The selected file is a directory.
setCurrentDirectory(file);
displayCurrentDirectory();
repaint();
_scrollPane.getViewport().setViewPosition(new Point(0,0));
_scrollPane.repaint();
/* If the newly selected directory is a root directory,
* don't allow the Parent button to be pressed.
*/
if (_isRoot(_currentDirectory) == false)
_parentButton.setEnabled(true);
}
/** Implements the FileChooserListener interface.
*/
public void fileChanged(FileChooserEvent e)
{
displayCurrentDirectory();
repaint();
}
private void _doNewDirectoryAction() {
JFileChooser.NewDirDialog dlg =
new NewDirDialog(this, _currentDirectory);
dlg.setLocation(getLocation().addOffset(2, 2));
dlg.show();
File newdir = dlg.getDirectory();
if (newdir != null)
setCurrentDirectory(newdir);
displayCurrentDirectory();
repaint();
}
private void _doParentDirectoryAction() {
if (_isRoot(_currentDirectory)) {
// We are already in a root directory. Display the
// filesystem roots in the listbox. The list of
// root directories is system-dependent; on Windows it
// would be A:, B:, C: etc. On Unix it would be "/".
File[] roots = File.listRoots();
for (int i=0; i<roots.length; i++) {
DefaultListModel listModel =
(DefaultListModel) _dirList.getModel();
listModel.addElement(roots[i].getAbsolutePath());
}
_location = "";
}
else {
File parent = _currentDirectory.getParentFile();
if (_isRoot(parent)) {
_parentButton.setEnabled(false);
_dirList.requestFocus();
}
setCurrentDirectory(parent);
displayCurrentDirectory();
repaint();
}
}
private void _doApproveAction() {
File file = new File(_locationField.getText());
String errmsg = null;
if (_fileSelectionMode == DIRECTORIES_ONLY &&
file.isDirectory() == false) {
errmsg = "Entry is not a directory: ";
}
else if (_fileSelectionMode == FILES_ONLY &&
file.isDirectory()) {
setCurrentDirectory(file);
displayCurrentDirectory();
repaint();
return;
}
if (errmsg != null) {
String[] msgs = { errmsg, _locationField.getText() };
JOptionPane.showMessageDialog(
this, msgs, "Error", JOptionPane.ERROR_MESSAGE);
return;
}
_cancelWasPressed = false;
_location = _locationField.getText();
hide();
}
private void _doCancelAction() {
_cancelWasPressed = true;
hide();
}
/** Returns true if the specified file is a root directory.
*/
private boolean _isRoot(File dir_) {
String dirname = dir_.getAbsolutePath();
File[] roots = File.listRoots();
for (int i=0; i<roots.length; i++) {
if (roots[i].getAbsolutePath().equals(dirname))
return true;
}
return false;
}
/**
* Causes the JFileChooser to scan its file list for the current
* directory, using the currently selected file filter if applicable.
* Note that this method does not cause the file chooser to be redrawn.
*/
private void displayCurrentDirectory()
{
/* Clear the list of Files in the current dir
*/
_dirList.clear();
DefaultListModel listModel = (DefaultListModel) _dirList.getModel();
/* Add all the current directory's children into the list.
*/
File[] files = _currentDirectory.listFiles();
/* Define and instantiate an anonymous class that implements
* the Comparator interface. This will be used by the TreeSet
* to keep the filenames in lexicographical order.
*/
Comparator fileSorter = new Comparator() {
public int compare(Object obj1, Object obj2) {
String file1 = (String) obj1;
String file2 = (String) obj2;
return file1.compareTo(file2);
}
};
TreeSet dirs = new TreeSet(fileSorter);
int numEntries = 0;
for (int i=0; i<files.length; i++) {
if (files[i].isDirectory()) {
dirs.add(files[i].getName() + "/");
}
else if ((_fileSelectionMode != DIRECTORIES_ONLY) &&
(_fileFilter == null ||
_fileFilter.accept(files[i]))) {
/* This is a regular file, and either there is no
* file filter or the file is accepted by the
* filter.
*/
dirs.add(files[i].getName());
}
numEntries++;
}
/* Copy the filenames from the TreeSet to the JList widget
*/
Iterator iter = dirs.iterator();
while (iter.hasNext()) {
listModel.addElement(iter.next());
}
_locationField.setText(_location);
}
private JScrollPane _scrollPane;
protected JButton _cancelButton = new JButton("Cancel");
protected JButton _approveButton = new JButton("Open");
protected JButton _parentButton = new JButton("Parent Directory");
protected JButton _newButton = new JButton("New Directory");
private JTextField _locationField = new JTextField(35);
}
/*====================================================================
* This is a non-static inner class used by the JFileChooser
* to implement a sorted list of directory names. The user can
* find a directory quickly by entering the first few characters
* of the directory name.
*/
private class DirList
extends JList
{
DirList() {
super();
setVisibleRowCount(10);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
/** Clears the list of files displayed by this JList.
* Does not generate any ListSelectionEvents. (?)
*/
void clear() {
// Clear the selection model without notifying any
// ListSelectionListeners.
int min = getSelectionModel().getMinSelectionIndex();
if (min != -1) {
int max = getSelectionModel().getMaxSelectionIndex();
getSelectionModel().removeIndexInterval(min, max);
}
// Clear the contents of the data model.
((DefaultListModel) getModel()).clear();
_currentRow = 0;
_matchbuf.setLength(0);
}
/** Overrides corresponding method in JList, and allows the
* user to find a directory quickly by typing the first few letters
* of the filename.
*/
public void processKeyEvent(KeyEvent evt_)
{
int key = evt_.getKeyCode();
ListModel listmodel = super.getModel();
if (listmodel.getSize() > 0 &&
(key == KeyEvent.VK_BACK_SPACE ||
(key > ' ' && key < 255))) {
if (key == KeyEvent.VK_BACK_SPACE) {
if (_matchbuf.length() > 0) // truncate
_matchbuf.setLength(_matchbuf.length() - 1);
else
Toolkit.getDefaultToolkit().beep();
}
else
_matchbuf.append((char) key);
/* Scan through the items in the list until we get
* to an item that is lexicographically greater than the
* pattern we have typed.
*/
String matchstring = _matchbuf.toString();
int i;
for (i=0; i<listmodel.getSize(); i++) {
if (matchstring.compareTo(listmodel.getElementAt(i)) <= 0) {
break;
}
}
if (i == listmodel.getSize())
i--; // the loop completed.
String item = (String) listmodel.getElementAt(i);
if ( ! item.startsWith(matchstring))
Toolkit.getDefaultToolkit().beep();
_currentRow = i;
super.ensureIndexIsVisible(i);
}
super.processKeyEvent(evt_);
}
// INSTANCE VARIABLE
private StringBuffer _matchbuf = new StringBuffer();
}
/*====================================================================
* This is a non-static inner class used by the JFileChooser
* to get the name of the new directory to create.
*/
private class NewDirDialog
extends JDialog
implements ActionListener
{
NewDirDialog(Dialog owner_, File parent_) {
super(owner_);
setTitle("Enter the new directory name");
_parentFile = parent_;
setSize(60, 10);
JPanel midpan = new JPanel();
midpan.setBorder(new EmptyBorder(2,2,2,2));
midpan.add(new JLabel("Directory name:"));
_dirnameField = new JTextField(35);
_dirnameField.setActionCommand("dirname");
_dirnameField.addActionListener(this);
midpan.add(_dirnameField);
add(midpan, BorderLayout.CENTER);
_okButton = new JButton("OK");
_okButton.addActionListener(this);
_cancelButton = new JButton("Cancel");
_cancelButton.addActionListener(this);
JPanel southpan = new JPanel();
southpan.setLayout(new FlowLayout(FlowLayout.RIGHT, 1, 1));
southpan.add(_okButton);
southpan.add(_cancelButton);
add(southpan, BorderLayout.SOUTH);
pack();
}
public void actionPerformed(ActionEvent e_) {
String cmd = e_.getActionCommand();
if (cmd.equals("OK") || cmd.equals("dirname")) {
if (_parentFile.canWrite() == false) {
String[] msgs = {"Permission denied"};
JOptionPane.showMessageDialog(
this, msgs, "Error", JOptionPane.ERROR_MESSAGE);
return;
}
File newdir = new File(_parentFile, _dirnameField.getText());
boolean ok = newdir.mkdir();
if (ok == false) {
String[] msgs = {"Invalid directory"};
JOptionPane.showMessageDialog(
this, msgs, "Error", JOptionPane.ERROR_MESSAGE);
}
else {
_directory = newdir;
hide();
}
}
else if (cmd.equals("Cancel")) {
_directory = null;
hide();
}
}
File getDirectory() { return _directory; }
private File _parentFile;
private JButton _okButton;
private JButton _cancelButton;
private JTextField _dirnameField;
private File _directory = null;
}
// end of inner class NewDirDialog
private interface FileChooserListener
extends EventListener
{
public void fileChanged(FileChooserEvent e);
}
private class FileChooserEvent
extends java.util.EventObject
{
public FileChooserEvent(Object source_)
{
super(source_);
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?