This section realizes the small ball follows the mouse movement function, here to realize the mouse movement monitoring, the code is as follows:
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); 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 =; @Overridepublic void Paint (Graphics g) {G.setcolor (Color.White); G.filloval (x, Y, 20, 20);} @Overridepublic void mousedragged (MouseEvent e) {} @Overridepublic void mousemoved (MouseEvent e) {x=e.getx (); Y=e.gety () ; repaint ();}}
The code runs the following example:
On-Machine topic (beginner)-Mouse control Ball (Java)