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