本文介绍了在 Java 中选择文件夹目标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Java 的新手.我正在尝试动态选择文件位置来保存我的项目结果(在我的项目开始时启动).我使用了几个 FileDialog 示例,但每个示例都允许我选择文件而不是文件夹.
I am a newbie to Java. I am trying to dynamically choose the file location to save the outcome of my project (to be initiated at the very start of my project). I worked around with a few FileDialog examples, but each one of them allows me to choose a file and not a folder.
谁能帮我提供一个示例(或)链接到相同的示例?
Can anyone please help me with an example (or) link to one for the same?
推荐答案
你可以尝试这样的事情(如下所示:选择带有 JFileChooser 的目录):
You could try something like this (as shown here: Select a Directory with a JFileChooser):
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class DemoJFileChooser extends JPanel
implements ActionListener {
JButton go;
JFileChooser chooser;
String choosertitle;
public DemoJFileChooser() {
go = new JButton("Do it");
go.addActionListener(this);
add(go);
}
public void actionPerformed(ActionEvent e) {
chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//
// disable the "All files" option.
//
chooser.setAcceptAllFileFilterUsed(false);
//
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "
+ chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "
+ chooser.getSelectedFile());
}
else {
System.out.println("No Selection ");
}
}
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
public static void main(String s[]) {
JFrame frame = new JFrame("");
DemoJFileChooser panel = new DemoJFileChooser();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
这篇关于在 Java 中选择文件夹目标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!