小画板与鼠标事件
耿祥义
摘要通过一个编写一个“小画板”学习使用MouseAdapter和MouseMotionAdapter处理MouseEvent巩固教材的学习效果。MouseAdapter已经实现了MouseListener接口, 2.MouseMotionAdapter已经实现了MouseMotionListener接口。
一、左键拖动鼠标自由绘制
用户左键拖动鼠标触发MouseEvent,程序处理MouseEvent事件时,绘制鼠标拖动形成的轨迹,如图:
二、右键拖动鼠标清除绘制
用户右键拖动鼠标触发MouseEvent,程序处理MouseEvent事件时,清除左键拖动鼠标绘制的部分图形,如图所示意:
三、click鼠标清除全部绘制
用户click鼠标触发MouseEvent,程序处理MouseEvent事件时,清除左键拖动鼠标绘制的全部图形,如图所示意:
四、视频讲解
https://share.weiyun.com/em6WvGzi
1.PaintPoint类(负责点对象)
public class PaintPoint {
public int x;
public int y;
public boolean isPaint = true;
public PaintPoint(int x,int y){
this.x = x;
this.y = y;
}
public boolean equals(Object object){
PaintPoint p =(PaintPoint)object;
if(Math.abs(x-p.x)+Math.abs(y-p.y)
return true;
else
return false;
}
}
2.FreeDrawingBoard类(负责画板对象)
import java.util.ArrayList;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.BasicStroke;
public class FreeDrawingBoard extends JPanel{
ArrayList
list;//存放被绘制的点
Color c;
BasicStroke bs;//画笔线条的粗细
boolean isClear;
public FreeDrawingBoard(){
list= new ArrayList
();
bs=
new BasicStroke
(3f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER);
c = Color.blue;
addMouseListener(new ListenOne());
addMouseMotionListener(new ListenTwo());
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g_2d=(Graphics2D)g;
g_2d.setStroke(bs);
g_2d.setColor(c);
int i = 0;
if(list.size()==0)
return;
for(i=0;i
if(list.get(i).isPaint){
int xStart = (int)list.get(i).x;
int yStart = (int)list.get(i).y;
int xEnd = (int)list.get(i+1).x;
int yEnd = (int)list.get(i+1).y;
g_2d.drawLine(xStart,yStart,xEnd,yEnd);
}
}
}
class ListenOne extends MouseAdapter {
public void mousePressed(MouseEvent e){
//按下鼠标左键
if(e.getButton()==MouseEvent.BUTTON1){
isClear = false;
}
//按下鼠标右键
else if(e.getButton()==MouseEvent.BUTTON3){
isClear = true;
}
}
public void mouseReleased(MouseEvent e){
//以后不再绘制最后一个点
if(list.size()==0)
return;
list.get(list.size()-1).isPaint = false;
}
public void mouseClicked(MouseEvent e){
if(e.getClickCount()>=2){
for(PaintPoint point:list){
point.isPaint = false;
}
list.clear();
repaint();
}
}
}
class ListenTwo extends MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if(isClear == false){
list.add(new PaintPoint(x,y));
repaint();
}
else {
PaintPoint p = new PaintPoint(x,y);
for(PaintPoint point:list){
if(point.equals(p)){
point.isPaint = false;
}
}
repaint();
}
}
}
}
3.FreeDrawingBoard类(主类)
import javax.swing.JFrame;
public class DrawWindow extends JFrame{
FreeDrawingBoard drawer;
public DrawWindow(){
setTitle
("左键拖动鼠标自由绘制,右键拖动鼠标清除绘制,双击鼠标全部清除");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(10,10,800,600);
drawer = new FreeDrawingBoard();
add(drawer);
}
public static void main(String args[]){
new DrawWindow();
}
}
领取专属 10元无门槛券
私享最新 技术干货