本节实现小球跟随鼠标移动的功能,这里要实现鼠标移动监听,代码如下:
import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.Panel; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; public class KeyListenerDemo { public static void main(String[] args) { Frame frame = new Frame(); frame.setSize(800, 800); frame.setBackground(Color.BLACK); MyPanel myPanel = new MyPanel(); frame.add(myPanel); frame.addMouseMotionListener(myPanel); myPanel.addMouseMotionListener(myPanel); frame.show(); } } class MyPanel extends Panel implements MouseMotionListener { int x = 150; int y = 150; @Override public void paint(Graphics g) { g.setColor(Color.WHITE); g.fillOval(x, y, 20, 20); } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { x=e.getX(); y=e.getY(); repaint(); } }
代码运行实例如下:
时间: 2024-10-02 07:38:04