package com.main;
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class MassageDialogDeom {
private final int AREA_WIDTH=500;
private final int AREA_HEIGHT=400;
BufferedImage bufferedImage=null;
private MyCanvas myCanvas=new MyCanvas();
int preX=-1;
int prey=-1;
private Color forceColor=Color.red;
public void init(){
Frame simple_mapping = new Frame("simple mapping");
PopupMenu popupMenu = new PopupMenu();
MenuItem red = new MenuItem("red");
MenuItem green = new MenuItem("green");
MenuItem blue = new MenuItem("blue");
bufferedImage= new BufferedImage(AREA_WIDTH, AREA_HEIGHT, BufferedImage.TYPE_INT_BGR);
//定义变量,记录鼠标上一次所处的坐标
//通过位图获取Graphics
Graphics graphics = bufferedImage.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0,0,AREA_WIDTH,AREA_HEIGHT);
myCanvas.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {//鼠标按下并拖动时会被调用
System.out.println("---"+e.getX()+"y"+e.getY());
if(preX>0&&prey>0){
graphics.setColor(forceColor);
//画线条
graphics.drawLine(preX,prey,e.getX(),e.getY());
myCanvas.repaint();
}
preX=e.getX();
prey=e.getY();
}
});
//通过监听鼠标的移动,完成线条绘制
//自定义一个类继承Canvas
ActionListener actionListener=new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
switch (actionCommand){
case "red":
forceColor=Color.red;
break;
case "green":
forceColor=Color.green;
break;
case "blue":
forceColor=Color.blue;
break;
}
}
};
red.addActionListener(actionListener);
green.addActionListener(actionListener);
blue.addActionListener(actionListener);
popupMenu.add(red);
popupMenu.add(green);
popupMenu.add(blue);
//把colormenu设置给绘图区域
myCanvas.add(popupMenu);
myCanvas.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
//当鼠标键抬起调用
boolean popupTrigger = e.isPopupTrigger();
if(popupTrigger){
popupMenu.show(myCanvas,e.getX(),e.getY());
}
preX=-1;
prey=-1;
}
});
myCanvas.setPreferredSize(new Dimension(AREA_WIDTH,AREA_HEIGHT));
simple_mapping.add(myCanvas);
simple_mapping.pack();
simple_mapping.setVisible(true);
}
private class MyCanvas extends Canvas{
@Override
public void paint(Graphics g) {
g.drawImage(bufferedImage,0,0,null);
}
}
public static void main(String[] args) {
new MassageDialogDeom().init();
}
}
image.png
网友评论