Java 中的文件选择器
Java Swing
包提供了在 Java 中选择文件的功能。本教程演示如何在 Java 中选择文件。
Java 中的文件选择器
Java Swing
包中的 JFileChooser
用于在 Java 中选择文件。Java™ 基础类 (JFC) 中的 Java Swing
包含许多用于构建 GUI 的功能。
JFileChooser
是用户选择目录或文件的一种有效且简单的方法。下表显示了一些用于不同选择的 JFileChooser
构造函数。
构造函数 | 描述 |
---|---|
JFileChooser() |
此构造函数将从默认目录中选择文件。 |
JFileChooser(文件当前目录) |
此构造函数将从当前目录中选择文件。 |
JFileChooser(字符串 currentDirectoryPath) |
此构造函数将从给定目录中选择文件。 |
让我们尝试一个使用 Java 中的 JFileChooser
选择文件的示例。
package delftstack;
import java.io.File;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
public class File_Chooser {
public static void main(String[] args) {
File_Chooser_Window();
}
private static void File_Chooser_Window() {
JFrame File_Chooser_Frame = new JFrame("File Chooser");
File_Chooser_Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Create_UI(File_Chooser_Frame);
File_Chooser_Frame.setSize(560, 200);
File_Chooser_Frame.setLocationRelativeTo(null);
File_Chooser_Frame.setVisible(true);
}
private static void Create_UI(final JFrame File_Chooser_Frame){
JPanel File_Chooser_Panel = new JPanel();
LayoutManager Layout_Manager = new FlowLayout();
File_Chooser_Panel.setLayout(Layout_Manager);
JButton Choose_Button = new JButton("Choose File");
final JLabel J_Label = new JLabel();
Choose_Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser J_File_Chooser = new JFileChooser();
J_File_Chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int option = J_File_Chooser.showOpenDialog(File_Chooser_Frame);
if(option == JFileChooser.APPROVE_OPTION){
File file = J_File_Chooser.getSelectedFile();
J_Label.setText("Selected: " + file.getName());
}
else{
J_Label.setText("Command Canceled");
}
}
});
File_Chooser_Panel.add(Choose_Button);
File_Chooser_Panel.add(J_Label);
File_Chooser_Frame.getContentPane().add(File_Chooser_Panel, BorderLayout.CENTER);
}
}
上面的代码将创建一个带有 Choose File
按钮的框架。请参阅下面的输出。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。