[java]左键画圆,右键画方

本文借用了别人的代码,稍加修改,实现了相关功能代码出处
题目大概意思:点击左键画圆,点击右键画方。
效果如图所示:
[java]左键画圆,右键画方_第1张图片
以下为我修改后的代码,仅供参考。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
 
public class Paint1 {
	public static void main(String[] args) {
		new MyFrame("drawPoint");
	}
}
 
class MyFrame extends JFrame{
	ArrayList points = null;
	int tag;
	
	MyFrame(String s){
		super(s);
		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.drawRoundRect(p.x,p.y,20,20,0,0);
			}else{
				System.out.println("请按规定操作");
			}
		}
	}
	
	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("leftkey");				
		}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("rightkey");	
		}				
	}
}

你可能感兴趣的:(java,左键画圆,右键画方)