package learn;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.net.http.HttpResponse;
import java.text.AttributedCharacterIterator;
public class HandDraw {
//窗口
private Frame frame = new Frame("简单手绘程序");
private final int AREA_WIDTH = 400;
private final int AREA_HIGHT = 300;
//菜单
private PopupMenu colorMenu = new PopupMenu();
private MenuItem redItem = new MenuItem("红色");
private MenuItem greenItem = new MenuItem("绿色");
private MenuItem blueItem = new MenuItem("蓝色");
//画笔的颜色
private Color forceColor = Color.BLACK;
//位图对象
BufferedImage image = new BufferedImage(AREA_WIDTH,AREA_HIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g= image.getGraphics();
public class MyCanvas extends Canvas
{
@Override
public void paint(Graphics g) {
g.drawImage(image,0,0,null);
}
}
MyCanvas drawArea = new MyCanvas();
//记录鼠标先前的位置
private int preX = -1;
private int preY = -1;
public void init()
{
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String actionCommend = e.getActionCommand();
switch (actionCommend){
case "红色":
forceColor = Color.red;
break;
case "绿色":
forceColor = Color.green;
break;
case "蓝色":
forceColor = Color.blue;
break;
}
}
};
redItem.addActionListener(listener);
greenItem.addActionListener(listener);
blueItem.addActionListener(listener);
colorMenu.add(redItem);
colorMenu.add(greenItem);
colorMenu.add(blueItem);
drawArea.add(colorMenu);
drawArea.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
boolean popupTrigger = e.isPopupTrigger();
if(popupTrigger)
{
colorMenu.show(drawArea,e.getX(),e.getY());
}
//重置
preX = -1;
preY = -1;
}
});
//背景为白色
g.setColor(Color.white);
g.fillRect(0,0,AREA_WIDTH,AREA_HIGHT);
drawArea.addMouseMotionListener(new MouseMotionAdapter() {
@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_WIDTH,AREA_HIGHT));
frame.add(drawArea);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new HandDraw().init();
}
}