import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class answer_007 {
public static void main(String[] args) {
new MyFrame("drawPoint");
}
}
class MyFrame extends JFrame{
ArrayList points = null;
int tag;//检测左键右键
MyFrame(String s){
super(s);//继承方法
this.setBackground(Color.white);
points= new ArrayList();
setLayout(null);//取消布局
setBounds(350,350,400,300);//设定窗口大小位置
this.addMouseListener(new Monitor());//加入监听器
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//可关闭窗口
}
public void paint(Graphics g) {
Iterator i = points.iterator();
while(i.hasNext()) {
Point p = (Point)i.next();
if(tag==1){//画圆
g.setColor(Color.green);
g.fillOval(p.x,p.y,20,20);
}else if(tag==2){//画方
g.setColor(Color.red);
g.fillRoundRect(p.x,p.y,20,20,0,0);
}
if(tag == 3){//清屏
g.clearRect(0, 0, 400, 300);
}
}
}
public void addPoint(Point p) {
points.add(p);//添加坐标
}
public void clearPoint(Point p) {
points.clear();//清除坐标
}
}
class Monitor extends MouseAdapter{
public void mousePressed(MouseEvent e) {
MyFrame mf = (MyFrame)e.getSource();
if(e.getButton() == e.BUTTON1){
mf.clearPoint(new Point(e.getX(),e.getY()));
mf.addPoint(new Point(e.getX(),e.getY()));//得到坐标
mf.tag=1;
mf.repaint();
System.out.println("左键"); //输出鼠标动作
}else if(e.getButton() == e.BUTTON3){
mf.clearPoint(new Point(e.getX(),e.getY()));
mf.addPoint(new Point(e.getX(),e.getY()));//得到坐标
mf.tag=2;
mf.repaint();
System.out.println("右键"); //输出鼠标动作
}
if(e.getClickCount() == 2){
mf.tag = 3;
System.out.println("双击");//输出鼠标动作
}
}
}
评论0