JFileChooser
类是一个为用户提供选择文件的简单机制的组件。
类声明
以下是javax.swing.JFileChooser
类的声明 -
public class JFileChooser
extends JComponent
implements Accessible
类字段
以下是javax.swing.JFileChooser
类的字段 -
类构造函数
以下是javax.swing.JFileChooser
类的构造函数 -
编号 | 构造函数 | 描述 |
---|---|---|
1 | JFileChooser() |
构造一个指向用户默认目录的JFileChooser 实例。 |
2 | JFileChooser(File currentDirectory) |
使用给定的文件作为路径构造JFileChooser 实例。 |
3 | JFileChooser(File currentDirectory, FileSystemView fsv) |
使用给定的当前目录和FileSystemView 构造JFileChooser 实例。 |
4 | JFileChooser(FileSystemView fsv) |
使用给定的FileSystemView 构造一个JFileChooser 实例。 |
5 | JFileChooser(String currentDirectoryPath) |
使用给定路径构造JFileChooser 实例。 |
6 | JFileChooser(String currentDirectoryPath, FileSystemView fsv) |
使用给定的当前目录路径和FileSystemView 构造JFileChooser 。 |
类方法
以下是javax.swing.JFileChooser
类的方法 -
方法继承
该类继承以下类中的方法 -
javax.swing.JComponent
java.awt.Container
java.awt.Component
java.lang.Object
JFileChooser示例
使用编辑器创建以下Java程序:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFileChooserExample {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public JFileChooserExample() {
prepareGUI();
}
public static void main(String[] args) {
JFileChooserExample swingControlDemo = new JFileChooserExample();
swingControlDemo.showFileChooserDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("Java Swing JFileChooser示例(yiibai.com)");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("", JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showFileChooserDemo() {
headerLabel.setText("Control in action: JFileChooser");
final JFileChooser fileDialog = new JFileChooser();
JButton showFileDialogButton = new JButton("选择文件...");
showFileDialogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = fileDialog.showOpenDialog(mainFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
java.io.File file = fileDialog.getSelectedFile();
statusLabel.setText("选择文件 :" + file.getName());
} else {
statusLabel.setText("用户取消打开文件");
}
}
});
controlPanel.add(showFileDialogButton);
mainFrame.setVisible(true);
}
}
执行上面示例代码,得到以下结果: