java基于GUI实现简单画笔小画板
在一块画板上实现鼠标点击画图案的功能(本文未实现拖动划线功能),供大家参考,具体内容如下
思路
与java设计GUI的大体思路一致, 先设置Frame类作为框架, 其中添加组件类作为功能补充. 该设计中需要设置鼠标监听类, 给frame加上组件
this.addMouseListener(new MyMouseListener());
并自己实现一个监听类, implements需要重写所有方法, 所以使用适配器
private class MyMouseListener extends MouseAdapter
给全局一个points数组变量, 保存所有点击的点的信息, 然后重写frame类的paint方法时改成迭代器依次画数组中的点
@Override public void paint(Graphics g) { // paint listen on mouse event Iterator iterator = points.iterator(); while (iterator.hasNext()){ Point point = (Point) iterator.next(); g.setColor(Color.GREEN); g.fillOval(point.x, point.y, 10, 10); } }
完整代码
import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Iterator; public class testmousepaint { public static void main(String[] args) { MyFrame myFrame = new MyFrame("IDEA"); } } class MyFrame extends Frame{ ArrayList points; public MyFrame(String title) { super(title); setBounds(200, 200, 400, 400); this.addMouseListener(new MyMouseListener()); setVisible(true); setBounds(200,200,400,400); setBackground(Color.white); points = new ArrayList<>(); } @Override public void paint(Graphics g) { // paint listen on mouse event Iterator iterator = points.iterator(); while (iterator.hasNext()){ Point point = (Point) iterator.next(); g.setColor(Color.GREEN); g.fillOval(point.x, point.y, 10, 10); } } public void addpoint(Point point){ points.add(point); } private class MyMouseListener extends MouseAdapter{ @Override public void mousePressed(MouseEvent e) { MyFrame frame = (MyFrame) e.getSource(); frame.addpoint(new Point(e.getX(), e.getY())); // click and paint every time frame.repaint(); } } }
实现效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)