本節實現小球跟隨鼠標移動的功能,這裡要實現鼠標移動監聽,代碼如下:
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(); } }