/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package handdraw;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
/**
*
* @author 91152
*/
public class HandDraw {
// 画图区的宽度
private final int AREA_WIDTH = 500;
// 画图区的高度
private final int AREA_HEIGHT = 400;
// 下面的preX、preY保存了上一次鼠标拖动事件的鼠标坐标
private int preX = -1;
private int preY = -1;
// 定义一个右键菜单用于设置画笔颜色
JPopupMenu pop = new JPopupMenu();
JMenuItem redItem = new JMenuItem("红色");
JMenuItem greenItem = new JMenuItem("绿色");
JMenuItem blueItem = new JMenuItem("蓝色");
BufferedImage image = new BufferedImage(AREA_WIDTH,
AREA_HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
private JFrame jf = new JFrame("简单手绘程序");
private MyJPanel drawArea = new MyJPanel();
private Color foreColor = new Color(255,0,0);
public void init(){
ActionListener menuListener = e ->{
if(e.getActionCommand().equals("绿色")){
foreColor = new Color(0,255,0);
}
if(e.getActionCommand().equals("红色")){
foreColor = new Color(255,0,0);
}
if(e.getActionCommand().equals("蓝色")){
foreColor = new Color(0,0,255);
}
};
redItem.addActionListener(menuListener);
greenItem.addActionListener(menuListener);
blueItem.addActionListener(menuListener);
pop.add(redItem);
pop.add(greenItem);
pop.add(blueItem);
drawArea.add(pop);
g.fillRect(0, 0, AREA_WIDTH, AREA_HEIGHT);
drawArea.setPreferredSize(new Dimension(AREA_WIDTH,AREA_HEIGHT));
drawArea.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
if(preX >0 && preY >0){
g.setColor(foreColor);
//这个设计很精巧
g.drawLine(preX,preY,e.getX(),e.getY());
}
preX = e.getX();
preY = e.getY();
drawArea.repaint();
}
});
drawArea.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
if(e.isPopupTrigger()){
pop.show(drawArea, e.getX(), e.getY());
}
preX=-1;
preY = -1;
}
});
jf.add(drawArea);
jf.pack();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
public static void main(String[] args) {
new HandDraw().init();
}
class MyJPanel extends JPanel{
@Override
public void paint(Graphics g){
//super.paint(g);
g.drawImage(image, 0, 0, null);
}
}
}