簡體   English   中英

如何使用 JFileChooser 查找文件位置

[英]How to use JFileChooser to find a file location

有沒有一種方法可以用來簡單地查找文件位置? 我試圖允許用戶選擇一個文件並打開它,但我必須讓 JFileChooser 只選擇文件並將位置發送到另一種方法。 做到這一點的最佳方法是什么?

javadoc show 中的示例顯示執行此操作:

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}

這就是chooser.getSelectedFile()正在做的。 獲取結果並將其傳遞給另一個方法。

chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

// You can use 
// chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);  too

File file = chooser.getSelectedFile();
String fullPath = file.getAbsolutePath();

然后將字符串傳遞給另一個方法。

我們也可以使用TextArea 來獲取Image File 的任意文件示例的路徑,對象TextArea 的名稱為txtPath,我們使用以下方法將ActionPerformed 設置為名為bChoose 的JButton。

JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "gif");
fc.setFileFilter(filter);
fc.showDialog(bChoose, "Choose File");
String strPath = txtPath.getText() + "\n" + fc.getSelectedFile().toString();
txtPath.setText(strPath);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM