默認(rèn)情況下沒有Windows那種豎排的文件夾選擇框,但可以通過FileDialog或JFileChooser設(shè)定參數(shù)令文件選取方式為[文件夾],給您寫了個(gè)小例子。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class MyFrame extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFileChooser fileChooser = new JFileChooser(".");
private JButton button = new JButton("打開文件");
public MyFrame() {
this.setTitle("文件夾選擇");
this.setPreferredSize(new Dimension(200, 100));
this.getContentPane().add(button, BorderLayout.NORTH);
button.addActionListener(this);
this.pack();
this.setLocationRelativeTo(null);
this.setIgnoreRepaint(true);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
// 觸發(fā)JButton(此例僅設(shè)置有一個(gè)按鈕,多按鈕請自行更改)
if (source instanceof JButton) {
openFile();
}
}
public void openFile() {
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setDialogTitle("打開文件夾");
int ret = fileChooser.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION) {
//文件夾路徑
System.out.println(fileChooser.getSelectedFile().getAbsolutePath());
}
}
public static void main(String[] args) {
Frame frame = new MyFrame();
frame.setVisible(true);
}
}