如何使用 JFileChooser 打开一个或多个文件
JFileChooser 是创建用于打开、保存和查看文件和文件夹的对话框的好方法。要从开头调出 JFileChooser 对话框,只需键入以下两行代码:
//创建文件选择器
JFileChooser fc = 新的 JFileChooser();
//点击按钮时的响应
int 返回 = fc.showOpenDialog(component_parent);
showOpenDialog 打开打开对话框。此方法返回三个可能的值之一,这些值提及用户选择的选项:
- JFileChooser.CANCEL_OPTION:用户尚未打开;
- JFileChooser.APPROVE_OPTION:用户已验证开口;
- JFileChooser.ERROR_OPTION:发生错误。
此代码将打开对话框,选择并加载所选文件:
import java.awt.BorderLayout;输出:
导入 java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
导入 java.io.File;
import javax.swing.JFileChooser;
导入 javax.swing.JFrame;
import javax.swing.JMenu;
导入 javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class JFileChooserTest {
public static void main(String[] args) {
final JFrame window = new JFrame();
window.setSize(200,200);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
JMenuBar jmb = new JMenuBar();
JMenu jm = new JMenu(Ficher”);
JMenuItem Open = new JMenuItem(Open”);
jm.add(打开);
jmb.add(jm);
window.add(jmb,BorderLayout.NORTH);
JFileChooser fc = new JFileChooser();
Open.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO 自动生成的方法 stub
int val_retour = fc.showOpenDialog(window);
if (val_retour == JFileChooser.APPROVE_OPTION) {
文件文件 = fc.getSelectedFile();
//显示文件名
System.out.println(文件名: ”+file.getName()+\n”);
//显示文件的绝对路径
System.out.println(绝对路径:”+file.getAbsolutePath()+\n”);
} else {
System.out.println(打开已取消\n”);
}
}
});
}
}
点击打开”后的终端屏幕:
文件名: decTo Binaire.cpp要检索所选文件,请使用方法 getSelectedFile()。如果返回值为JFileChooser.APPROVE_OPTION,返回值是 class File.
文件名:C:\Users\VAIO\Documents\CC++\decTo Binaire.cpp
文件名和绝对路径的实例,使用 getName() 和 getAbsolutePath() 分别。如果用户取消该操作,则会显示一条消息,指示取消。
JFileChooser 允许您选择一个或多个文件。要全部打开它们,我们必须修改代码。更改位于实例声明中 File它将成为选定文件的数组。我们还应该要求 JFileChooser 让我们可以使用 setMultiSelectionEnabled().
final JFileChooser fc = new JFileChooser();Runtime:
fc.setMultiSelectionEnabled(true)
Open.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO 自动生成的方法 stub
int val_retour = fc.showOpenDialog(window);
if (val_retour == JFileChooser.APPROVE_OPTION) {
File[] file = fc.getSelectedFiles();
//遍经文件集的循环
for(File f:file){
System.out.println(文件名: ”+f.getName()+\n”);
System.out.println(绝对路径:”+f.getAbsolutePath()+\n”);
}
} else {
System.out.println(打开已取消\n”);
}
}
});
文件名:decTo Binaire.cppReferences:
绝对路径:C:\Users\VAIO\Documents\CC++\decTo Binaire.cpp
文件名:decalage_tableau.cpp
绝对路径:C:\Users\VAIO\Documents\CC++\decalage_tableau.cpp
文件名: determinant_matrice.cpp
绝对路径:C:\Users\VAIO\Documents\CC++\determinant_matrice.cpp
文件名:equation-1-degre.cpp
绝对路径:C:\Users\VAIO\Documents\CC++\equation-1-degre.cpp
创建 JMenuBar 组件:JMenuBar
Java 文档:showOpenDialog 方法