import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FileChooserTest extends JFrame {
public FileChooserTest(){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JButton bt=new JButton("打开");
this.add(bt);
final JTextField tf=new JTextField(20);
this.add(tf);
final JTextField tf2=new JTextField(20);
this.add(tf2);
bt.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JFileChooser file=new JFileChooser();
int val=file.showOpenDialog(FileChooserTest.this);
if(val==file.APPROVE_OPTION)
{
tf.setText(file.getSelectedFile().getName());
tf2.setText(file.getCurrentDirectory().toString()+file.getSelectedFile().getName());
}
else
{
tf.setText("你取消了");
tf2.setText("");
}
}});
this.setLayout(new FlowLayout());
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100,100,200,200);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new FileChooserTest();
}
}