2014-04-16 31 views
2

我需要在javax.swing.JFileChooser的標籤爲'文件名'的文本字段中獲取最新的輸入文本。如何聆聽JFileChooser中'文件名'TextField的更改?

我不需要最新選定的文件,因爲輸入到「文件名」中的文本應該作爲新創建文件的名稱。

我使用了SELECTED_FILE_CHANGED_PROPERTY,但它僅在文件選擇上被觸發。 還有FILE_FILTER_CHANGED_PROPERTY,但當我更改文件類型時它會被觸發。

如何聆聽「文件名」文本字段的更改?

謝謝!

回答

2

注意:SELECTED_FILE_CHANGED_PROPERTY僅當選擇單個項目時才觸發事件。

特別是,如果在啓用多選模式時選擇了多個項目,則不會觸發此事件。但是,如果在多選模式下選擇單個項目,則會觸發此事件。

當處於多選模式時,無論是否選擇單個或多個文件,總是會觸發SELECTED_FILES_CHANGED_PROPERTY事件。

JFileChooser chooser = new JFileChooser(); 

// Add listener on chooser to detect changes to selected file 
chooser.addPropertyChangeListener(new PropertyChangeListener() { 
    public void propertyChange(PropertyChangeEvent evt) { 
     if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY 
       .equals(evt.getPropertyName())) { 
      JFileChooser chooser = (JFileChooser)evt.getSource(); 
      File oldFile = (File)evt.getOldValue(); 
      File newFile = (File)evt.getNewValue(); 

      // The selected file should always be the same as newFile 
      File curFile = chooser.getSelectedFile(); 
     } else if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(
       evt.getPropertyName())) { 
      JFileChooser chooser = (JFileChooser)evt.getSource(); 
      File[] oldFiles = (File[])evt.getOldValue(); 
      File[] newFiles = (File[])evt.getNewValue(); 

      // Get list of selected files 
      // The selected files should always be the same as newFiles 
      File[] files = chooser.getSelectedFiles(); 
     } 
    } 
}) ; 
+0

-1,因爲博洛迪亞要添加一個監聽器。 –

+0

@das_j>你說得對。我會更新我的答案,請稍後再查看。 – mok

+0

非常感謝。但我需要從JFileChooser中標記爲「文件名」的textField中獲取文本。用戶可以根本不選擇任何文件,但只有類型文件名和程序應該創建這樣的文件。 –

1

你想要的是一個JFileChooserSAVE_DIALOG標誌。

一些演示代碼:

JFileChooser chooser = new JFileChooser("some path"); 
chooser.setDialogType(JFileChooser.SAVE_DIALOG); 
// Stuff like setting the required file extension, the title, ... 
int result = chooser.showSaveDialog(this); 
if (result == JFileChooser.APPROVE_OPTION) { 
    String path = chooser.getSelectedFile().toString(); 
    // Do something with the path 
} 
chooser.setVisible(false); // Don't forget to hide