import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
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;
//定义一个右键菜单用地设置画笔颜色
PopupMenu pop=new PopupMenu();
MenuItem redItem=new MenuItem("红色");
MenuItem greenItem=new MenuItem("绿色");
MenuItem blueItem=new MenuItem("蓝色");
//定义一个BufferedImage对象
BufferedImage image=new BufferedImage(AREA_WIDTH,AREA_HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
private Frame f=new Frame("简单手绘程序");
private DrawCanvas drawArea=new DrawCanvas();
private Color foreColor=new Color(255,0,0);
public void init(){
ActionListener menuListener=new ActionListener(){
public void actionPerformed(ActionEvent 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对象中
drawArea.add(pop);
//将image对象的背景色填充成白色
g.fillRect(0,0,AREA_WIDTH,AREA_HEIGHT);
drawArea.setPreferredSize(new Dimension(AREA_WIDTH,AREA_HEIGHT));
//监听鼠标移动动作
drawArea.addMouseMotionListener(new MouseMotionAdapter(){
public void actionPerformed(MouseEvent e){
//如果preX和preY大于0
if(preX>0&&preY>0){
//设置当前颜色
g.setColor(foreColor);
//绘制从上一次鼠标拖动事件到本次鼠标拖动事件点的线段
g.drawLine(preX, preY, e.getX(),e.getY());
}
//将当前鼠标事件点的X、Y坐标保存起来
preX=e.getX();
preY=e.getY();
//重绘drawArea对象
drawArea.repaint();
}
});
//监听鼠标事件
drawArea.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
if(e.isPopupTrigger()){
pop.show(drawArea, e.getX(), e.getY());
}
//松开鼠标键时,把上一次鼠标拖动事件的X、Y坐标设为-1
preX=-1;
preY=-1;
}
});
f.add(drawArea);
f.pack();
f.setVisible(true);
}
public static void main(String[] args){
new HandDraw().init();
}
class DrawCanvas extends Canvas{
public void paint(Graphics g){
//将image绘制到该组件上
g.drawImage(image,0,0,null);
}
}
}
程序代码如上面所示,界面有,右键菜单也有,颜色也能选到,但画不了东西····又是眼睛看瞎了都没搞清楚啥事,求大神指点
|
|