注释很详细,直接上代码
package swing21_30;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class swing_test_23 {
private Frame frame=new Frame("swing_test_23");
MenuBar menuBar=new MenuBar();
Menu menu=new Menu("文件");
MenuItem open=new MenuItem("打开");
MenuItem save=new MenuItem("另存为");
//声明BufferedImage对象,记录本地图片
BufferedImage image;
private class MyCanvas extends Canvas{
@Override
public void paint(Graphics g){
g.drawImage(image,0,0,null);
}
}
MyCanvas drawArea=new MyCanvas();
public void init() throws Exception{
//组装视图
open.addActionListener(e -> {
//打开文件
FileDialog fileDialog=new FileDialog(frame,"打开图片",FileDialog.LOAD);
fileDialog.setVisible(true);
//获取用户选择的图片路径以及名称
String dir=fileDialog.getDirectory();
String filename=fileDialog.getFile();
try{
image= ImageIO.read(new File(dir+filename));
drawArea.repaint();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
save.addActionListener(e->{
//展示一个文件对话框
FileDialog fileDialog=new FileDialog(frame,"保存图片",FileDialog.SAVE);
fileDialog.setVisible(true);
//获取用户设置的保存路径和文件名称
String dir=fileDialog.getDirectory();
String filename=fileDialog.getFile();
try{
ImageIO.write(image,"JPEG",new File(dir,filename));
}catch (IOException ex){
ex.printStackTrace();
}
});
// 设置窗口大小
frame.setBounds(200,200,740,508);
// 显示窗口
frame.setVisible(true);
// 关闭窗口时退出程序
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// 菜单栏
menu.add(open);
menu.add(save);
menuBar.add(menu);
//把菜单条目添加到菜单栏中
frame.setMenuBar(menuBar);
frame.add(drawArea);//把画布添加到窗口中
frame.setBounds(200,200,740,508);
frame.setVisible(true);
}
public static void main(String[] args) {
//直接运行init
try {
new swing_test_23().init();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
运行效果