java AWT 图片查看器
java AWT 图片查看器
1 package io.guanghe;
2
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.awt.image.BufferedImage;
6
7 public class DrawImage {
8 private Frame frame = new Frame("光何绘图");
9 private final int AREA_WIDTH = 500;
10 private final int AREA_HEIGHT = 400;
11 private PopupMenu colorMenu = new PopupMenu();
12 private MenuItem redItem = new MenuItem("red");
13 private MenuItem greenItem = new MenuItem("green");
14 private MenuItem blueItem = new MenuItem("blue");
15 private Color forceColor = Color.BLACK;
16 BufferedImage image = new BufferedImage(AREA_WIDTH, AREA_HEIGHT, BufferedImage.TYPE_INT_RGB);
17 Graphics g = image.getGraphics();
18 private class MyCanvas extends Canvas {
19 @Override
20 public void paint(Graphics g) {
21 g.drawImage(image, 0, 0, null);
22 }
23 }
24 MyCanvas canvas = new MyCanvas();
25 private int preX = -1;
26 private int preY = -1;
27
28 public void init() {
29 frame.addWindowListener(new WindowAdapter() {
30 @Override
31 public void windowClosing(WindowEvent e) {
32 System.exit(0);
33 }
34 });
35 ActionListener listener = e -> {
36 String actionCommand = e.getActionCommand();
37 switch(actionCommand) {
38 case "red":
39 forceColor = Color.RED;
40 break;
41 case "green":
42 forceColor = Color.GREEN;
43 break;
44 case "blue":
45 forceColor = Color.BLUE;
46 break;
47 }
48 };
49 redItem.addActionListener(listener);
50 greenItem.addActionListener(listener);
51 blueItem.addActionListener(listener);
52 colorMenu.add(redItem);
53 colorMenu.add(greenItem);
54 colorMenu.add(blueItem);
55 canvas.add(colorMenu);
56 canvas.addMouseListener(new MouseAdapter() {
57 @Override
58 public void mouseReleased(MouseEvent e) {
59 if(e.isPopupTrigger()) {
60 colorMenu.show(canvas, e.getX(), e.getY());
61 }
62 preX = -1;
63 preY = -1;
64 }
65 });
66 g.setColor(Color.WHITE);
67 g.fillRect(0, 0, AREA_WIDTH, AREA_HEIGHT);
68 canvas.addMouseMotionListener(new MouseMotionAdapter() {
69 @Override
70 public void mouseDragged(MouseEvent e) {
71 if(preX > 0 && preY > 0) {
72 g.setColor(forceColor);
73 g.drawLine(preX, preY, e.getX(), e.getY());
74 }
75 preX = e.getX();
76 preY = e.getY();
77 canvas.repaint();
78 }
79 });
80 canvas.setPreferredSize(new Dimension(AREA_WIDTH, AREA_HEIGHT));
81 frame.add(canvas);
82 frame.pack();
83 frame.setVisible(true);
84 }
85
86 public static void main(String[] args) {
87 new DrawImage().init();
88 }
89 }