注释很详细,直接上代码
新增内容
1.ImageIO.write读取并显示图片
2.ImageIO.writeImageIO.write读取并保存图片
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{@Overridepublic 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() {@Overridepublic 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) {//直接运行inittry {new swing_test_23().init();} catch (Exception e) {throw new RuntimeException(e);}}
}
运行效果