这是个完成点击按钮弹出文件选择框,并把用户选择的文件路径显示在lable中的功能:
class saveAction implements ActionListener{
public void actionPerformed(ActionEvent arg0){
UIManager.put("FileChooser.cancelButtonText", "Cancel Button"); //修改取消
UIManager.put("FileChooser.saveButtonText", "Save Button"); //修改保存
UIManager.put("FileChooser.openButtonText", "Open Button");//修改打开
JFileChooser fc = new JFileChooser();//实例化一个filechooser*/
fc.setDialogTitle("选择文件...");//设置Filechooser的标签
fc.setApproveButtonText("选择");
int result=fc.showOpenDialog(fc);
if(result==JFileChooser.APPROVE_OPTION)//定义确认按钮的行为
{
String fileName=fc.getCurrentDirectory()+"\\"+fc.getSelectedFile().getName();//设置已获取文件的路径及文件名
filepath.setText(fileName);
}
}
}
其中这3句要写在filechooser初始化之前:
UIManager.put("FileChooser.cancelButtonText", "Cancel Button"); //修改取消
UIManager.put("FileChooser.saveButtonText", "Save Button"); //修改保存
UIManager.put("FileChooser.openButtonText", "Open Button");//修改打开
其中int returnVal = fc.showOpenDialog(fc)有3个返回值
JfileChooser.Cancel_Option:取消
JfileChooser.Approve_Option:打开
JfileChooser.Error_Option:发生错误
File file = fc.getSelectedFile();
返回可能是个文件路径,也有可能是个文件夹路径。