第一种 JFileChooser
JLabel lblNewLabel_1 = new JLabel("");
JFileChooser jf=new JFileChooser();
jf.setDialogTitle("选择头像");
jf.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean accept(File dir) {
String name=dir.getName();
if (dir .isDirectory()||name.endsWith("jpg")||name.endsWith("gif")||name.endsWith("png"))
return true;
else
return false;
}
});
int result = jf.showOpenDialog(Stuinfo.this);
jf.setVisible(true);
File selectedFile = null;//选择的文件
if(result==JFileChooser.APPROVE_OPTION)
{
selectedFile = jf.getSelectedFile();
//文件存在
if(selectedFile.exists())
{
String fliepath=selectedFile.getPath();
ImageIcon iic=new ImageIcon(fliepath);
iic.setImage(iic.getImage().getScaledInstance(lblNewLabel_1.getWidth(),lblNewLabel_1.getHeight(),Image.SCALE_DEFAULT));
lblNewLabel_1.setIcon(iic);
}
}
第二种 FileDialog
FileDialog fd = new FileDialog(Stuinfo.this, "选择头像", FileDialog.LOAD);
//过滤文件
FilenameFilter filter=new FilenameFilter(){
public boolean accept(File dir, String name) {
if (name.endsWith("jpg")||name.endsWith("gif")||name.endsWith("png")){
return true;
}
return false;
}
};
fd.setFilenameFilter(filter);
fd.setVisible(true);
String f = fd.getFile();
String dir = fd.getDirectory();
if(f != null) {
ImageIcon iic=new ImageIcon(dir + fd.getFile());
iic.setImage(iic.getImage().getScaledInstance(lblNewLabel_1.getWidth(),lblNewLabel_1.getHeight(),Image.SCALE_DEFAULT));
lblNewLabel_1.setIcon(iic);
}
原文地址:http://blog.csdn.net/wangzhiqiang123456/article/details/39184227