GUI实现用鼠标画图
GUI实现用鼠标画图
以下代码模拟画板功能,用鼠标在指定位置画点。
package com.cxf.gui.five;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
public class PaintTest {
public static void main(String[] args) {
new MyFrame();
}
}
class MyFrame extends Frame{
ArrayList points= new ArrayList<>();;
public MyFrame(){
setBounds(400,400,700,500);
setVisible(true);
addMouseListener(new MyMouseListener());
}
private class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e){
//MyFrame frame = (MyFrame) e.getSource();
addPoint(new Point(e.getX(),e.getY()));
repaint(); // call for paint to paint all again
}
}
public void addPoint(Point point){
points.add(point);
}
public void paint(Graphics g){
for (Object o : points) {
Point point = (Point) o;
g.setColor(Color.BLUE);
g.fillOval(point.x, point.y, 10, 10);
}
}
}
main函数用了自定义类MyFrame。
MyFrame类中定义并添加了鼠标监听事件。
监听事件实现了储存点坐标和画点的功能。
输出结果:
鼠标单击左键即可画点。