62,615
社区成员
发帖
与我相关
我的任务
分享
JFileChooser jfc = new JFileChooser();
//System.out.println("choose done");
jfc.setFileSelectionMode(0);//设定只能选择到文件
int state = jfc.showOpenDialog(null);//此句是打开文件选择器界面的触发语句
if (state == 1) {
return;//撤销则返回
} else {
File f = jfc.getSelectedFile();//f为选择到的文件
jTextField1.setText(f.getAbsolutePath());
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class MainFrame extends JFrame implements ActionListener {
private JButton button;
private JFileChooser fileChooser;
public MainFrame() {
button = new JButton("浏览");
button.addActionListener(this);
fileChooser = new JFileChooser("./");
this.add(button,BorderLayout.NORTH);
this.setSize(800, 600);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
fileChooser.showOpenDialog(this);
}
public static void main(String[] args) {
new MainFrame();
}
}
JFileChooser chooser = new JFileChooser();
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the JDK.
ExampleFileFilter filter = new ExampleFileFilter();
filter.addExtension("jpg");
filter.addExtension("gif");
filter.setDescription("JPG & GIF Images");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}