画圆画方

来源:互联网 发布:网页交互设计 软件 编辑:程序博客网 时间:2024/05/17 22:24
//画圆画方import java.awt.*;import java.awt.event.*;import javax.swing.*;public class DrawCircleOrSquare extends JFrame{private static final long serialVersionUID = 1L;private MyPanel myPanel = null;    public DrawCircleOrSquare(){    myPanel = new MyPanel();//创建面板        myPanel.addMouseListener(myPanel);//添加鼠标监视器        myPanel.setBackground(Color.yellow);        this.add(myPanel,BorderLayout.CENTER);        this.setSize(960, 540);//设置窗体大小        this.setTitle("画圆画方");//设置窗体标题        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭窗口        this.setVisible(true);//设置窗体可见        } class MyPanel extends JPanel implements MouseListener{//定义鼠标监听器private static final long serialVersionUID = 1L;    int Click = 0;    public void mouseClicked(MouseEvent count) {    int x=count.getX();        int y=count.getY();        Click = count.getButton();//获取鼠标点击的次数        Graphics g = this.getGraphics();//重新绘制        if(Click==1){//如果是点击左键        if(count.getClickCount()==2){//如果是双击左键        g.setColor(Color.white);        g.fillRect(0, 0, 960, 540);//白色覆盖面板以实现橡皮擦功能        }        else if(count.getClickCount()==1){//如果是单击左键        g.setColor(Color.green);        g.fillOval(x, y, 30, 30);//填充长宽均为30的矩形的内切椭圆(即直径为30的圆)        }        }        else if(Click ==3){//如果是点击右键        g.setColor(Color.red);        g.drawRect(x, y, 30, 30);//画出长宽均为30的矩形        }         }    //设置鼠标事件的各种监听器    public void mouseEntered(MouseEvent c) {}//鼠标进入到组件上时调用    public void mouseExited(MouseEvent c) {}//鼠标退出组件时调用    public void mousePressed(MouseEvent c) {}//鼠标按下时调用    public void mouseReleased(MouseEvent c) {}//鼠标释放时调用}public static void main(String[] args){  new DrawCircleOrSquare();  }}

原创粉丝点击