```java
package com.one.draw;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
public class HandDraw {
Frame f = new Frame("简单手绘程序");
private final int AREA_WIRTH = 500;
private final int AREA_HIGHT = 400;
private PopupMenu pm = new PopupMenu();
private MenuItem redItem = new MenuItem("红色");
private MenuItem blueItem = new MenuItem("蓝色");
private MenuItem greenItem = new MenuItem("绿色");
private Color forceColor = Color.black;
BufferedImage bi = new BufferedImage(AREA_WIRTH, AREA_HIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
private class MyCanvas extends Canvas {
@Override
public void paint(Graphics g) {
g.drawImage(bi, 0, 0, null);
}
}
MyCanvas drawArea = new MyCanvas();
private int preX = -1;
private int preY = -1;
private void init() {
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "红色":
forceColor = Color.RED;
break;
case "蓝色":
forceColor = Color.BLUE;
break;
case "绿色":
forceColor = Color.GREEN;
break;
}
}
};
redItem.addActionListener(listener);
greenItem.addActionListener(listener);
blueItem.addActionListener(listener);
pm.add(redItem);
pm.add(greenItem);
pm.add(blueItem);
drawArea.add(pm);
drawArea.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
boolean popupTrigger = e.isPopupTrigger();
if (popupTrigger) {
pm.show(drawArea, e.getX(), e.getY());
}
preX = -1;
preY = -1;
}
});
g.setColor(Color.white);
g.fillRect(0, 0, AREA_WIRTH, AREA_HIGHT);
drawArea.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (preX > 0 && preY > 0) {
g.setColor(forceColor);
g.drawLine(preX, preY, e.getX(), e.getY());
}
preX = e.getX();
preY = e.getY();
drawArea.repaint();
}
});
drawArea.setPreferredSize(new Dimension(AREA_WIRTH, AREA_HIGHT));
f.add(drawArea);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new HandDraw().init();
}
}