打开源代码:publicvoidloadFile(){JButtonmsg=newJButton();JFileChooserchooser=newJFileChooser();//只显示文件夹和jpg格式的文件FileNameExtensionFilterfilter=newFileNameExten...
打开源代码:
public void loadFile(){
JButton msg = new JButton();
JFileChooser chooser = new JFileChooser();
// 只显示文件夹和jpg格式的文件
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.JPG", "jpg");//建立过滤器,只显示jpg
chooser.setFileFilter(filter);
chooser.setCurrentDirectory(new File(""));
int result =chooser.showOpenDialog(msg);
if(result ==JFileChooser.APPROVE_OPTION){
// 获取选择的文件
filename = chooser.getSelectedFile().getName();
// 获取文件路径
path = chooser.getCurrentDirectory().getPath();
// 获取文件路径下所有jpg文件
filterj = new Filter(FILE_TYPE);
File file = new File(path);
pics = file.list();
pics = file.list(filterj);
//跟踪选中的图片
for(int j=0;j
if(pics[j].equalsIgnoreCase(filename))
{
i=j;
break;
}
dir = path + "\\" + filename;
hasPic = true;
loadImage(dir);
//pathInfo.setForeground(Color.BLACK);
pathInfo.setText(path + "\\" + filename);
} else {
hasPic = false;
pathInfo.setForeground(Color.RED);
pathInfo.setText("没有选择文件!");
}
}
保存源代码:
//保存文件
public void saveFile() throws IOException {
JButton msgsave = new JButton();
JFileChooser chooser = new JFileChooser();
// 只显示文件夹和jpg格式的文件
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"*.JPG", "jpg");//建立过滤器,只显示jpg
chooser.setFileFilter(filter);
File fin = new File(path + "\\" + pics[i]);
File f = new File("" + "\\" + pics[i]);
chooser.setSelectedFile(f);
int returnVal = chooser.showSaveDialog(msgsave);
// 根据返回值判断是否选择了文件路径
if(returnVal == JFileChooser.APPROVE_OPTION) {
// 获取文件路径
path = chooser.getCurrentDirectory().getPath();
File fileout = new File(path + "\\" + chooser.getSelectedFile().getName());
FileInputStream isr = new FileInputStream(fin);
FileOutputStream fout = new FileOutputStream(fileout);
byte b[] = new byte[200];
int count = 0;
while((count = isr.read(b, 0, 200))!=-1)
fout.write(b,0,count);
isr.close();
fout.flush();
fout.close();
}
}
另外两个子类:
// 加载图像
public void loadImage(String filename) {
pic = this.getToolkit().getImage(filename); //取得图像
MediaTracker mt = new MediaTracker(this); //实例化媒体加载器,跟踪多种媒体对象状态
mt.addImage(pic, 0); //增加图像到加载器中
picWidth = pic.getWidth(this);
picHeight = pic.getHeight(this);
try {
mt.waitForAll(); // 等待图片加载
} catch (Exception e) {
e.printStackTrace(); //输出出错信息
}
oriBufImage = new BufferedImage(pic.getWidth(this),pic.getHeight(this),BufferedImage.TYPE_INT_ARGB);
bufImage = oriBufImage;
bufImageG = bufImage.createGraphics();
bufImageG.drawImage(pic, 0, 0, this);
repaint();
}
展开