学到按键监听,故想到了鼠标监听,以此记录下过程,简易作品勿喷。
监听鼠标,获取鼠标运动坐标,历史坐标都存入一个容器中,一个坐标画个圆,每次绘画,把所有坐标的圆画出来,就看起来形成笔画了
1.Writer extends JFame 初始化框体
2.MyPanel extends JPanel implent implements MouseMotionListener
3.存储X Y?于是想到了HashMap,好像还要有顺序?(总不能写个小字先出现了中间部分吧,好像画得很快,也看不出是从哪里画起的),那再来个LinkedhashMap;
当画到横坐标相同的笔画时,之前的消失了。
原理,Map接口下的子类是不允许有重复值的。
怎么办呢? 既要有顺序,由要有X,Y ,我可以将XY封装到一个对象里不就行吗
将数据的存储改为ArraysList 而且查询用的多
再class MyPanel extends JPanel implements MouseMotionListener, KeyListener
监听到特定键就清空ArraysList再重绘就之前的字没有啦
清空之后总是还有一个点。
import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.util.*; public class Writer extends JFrame { private MyPanel mp5; public static void main(String[] args) { new Writer(); } public Writer() { mp5 = new MyPanel(); this.add(mp5); this.setSize(700, 700); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); this.addMouseMotionListener(mp5); //鼠标监听 this.addKeyListener(mp5);//键盘监听 } } class MyPanel extends JPanel implements MouseMotionListener, KeyListener { int x = 0; int y = 0; //private HashMap<Integer, Integer> XY = new LinkedHashMap<>(); ArrayList<Coor> coors = new ArrayList<Coor>(); @Override public void paint(Graphics g) { super.paint(g); coors.add(new Coor(x, y)); Iterator<Coor> iterator = coors.iterator(); while (iterator.hasNext()) { Coor next = iterator.next(); g.fillOval(next.X,next.Y,15,15); System.out.println("=================" + next.X + " "+next.Y); } } @Override public void mouseDragged(MouseEvent e) { x = e.getX() - 15; y = e.getY() - 45; this.repaint(); System.out.println("鼠标在拖动" + e.getY() + " " + e.getY()); } @Override public void mouseMoved(MouseEvent e) { } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_R){ coors.clear(); x=0; y=0; this.repaint(); } System.out.println((char) e.getKeyCode() + "按键按下"); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } } class Coor { public int X; public int Y; public Coor(int x, int y) { X = x; Y = y; } }