首页 > 编程语言 > 详细

用java代码实现“用鼠标点击一个圆,并同时拖动鼠标,圆会变大并且同时改变颜色,移开鼠标停止拖动后,圆又恢复成起始大小和颜色”

时间:2019-05-09 14:38:26      阅读:204      评论:0      收藏:0      [点我收藏+]
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class DrawWithPanel extends JFrame{
   private static final long serialVersionUID=1L;
   DrawWithPanel(){
      super("可拖动的圆");
      this.getContentPane().add(new PaintPanel());
      this.setDefaultCloseOperation(EXIT_ON_CLOSE);
      this.setBounds(50,50,750,700);
      this.setVisible(true);
   }
   class PaintPanel extends JPanel implements MouseListener,MouseMotionListener{
    private static final long serialVersionUID=1L;
    Color color=new Color(0,0,0);
    int startX=130,startY=140,width=150,height=150;
    public PaintPanel() {
        addMouseListener(this);
        addMouseMotionListener(this);
    }
    protected void paintComponent(Graphics g) {
        g.setColor(Color.white);
        g.fillRect(0, 0, 750, 700);
        g.setColor(color);
        g.fillOval(startX, startY, width, height);
    }
    @Override
    public void mouseDragged(MouseEvent e) {
        color=Color.pink;
        startX=startX+2;
        startY=startY+2;
        width=width+2;
        height=height+2;
        repaint();
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        
        
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        color=Color.yellow;
        startX=130;
        startY=140;
        width=150;
        height=150;
        repaint();
        
    }

    @Override
    public void mousePressed(MouseEvent e) {
        
        
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        color=Color.blue;
        startX=130;
        startY=140;
        width=150;
        height=150;
        repaint();
        
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        
        
    }

    @Override
    public void mouseExited(MouseEvent e) {
        
        
    }
       
   }
   public static void main(String args[])
   {
       new DrawWithPanel();
   }
}

用java代码实现“用鼠标点击一个圆,并同时拖动鼠标,圆会变大并且同时改变颜色,移开鼠标停止拖动后,圆又恢复成起始大小和颜色”

原文:https://www.cnblogs.com/jianqiao123/p/10838117.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!