i making java applet, draws circle, need move circle random place when hover mouse coursor, right applet draws circle in random place , changes color when hover circle mouse, how make move random place? suggestions appreciated.
import java.awt.*; import java.applet.*; import java.awt.event.*; public class circle extends applet implements mousemotionlistener { // x-coordinate , y-coordinate of last mouse position. int xpos; int ypos; //generate random place circle (in coordinates 0 400 int x=(int)(math.random() * 401); int y=(int)(math.random() * 401); int width; int height; // wll true when mouse in circle boolean active; public void init() { width=40; height=40; // add mousemotionlistener applet addmousemotionlistener(this); } public void paint(graphics g) { if (active){g.setcolor(color.black);} else {g.setcolor(color.blue);} g.fillroundrect(x, y, width, height, 200, 200); // show coordinates of mouse // @ place of mouse. g.drawstring("("+xpos+","+ypos+")",xpos,ypos); } // excuted whenever mousemoves in applet public void mousemoved(mouseevent me) { xpos = me.getx(); ypos = me.gety(); // check if mouse in circle if (xpos > x&& xpos < x+width && ypos > y && ypos < y+height) active = true; else active = false; //show results of motion repaint(); } public void mousedragged(mouseevent me) { } }
just put copy of
x=(int)(math.random() * 401); y=(int)(math.random() * 401);
into condition in paint() method
public void paint(graphics g) { if (active){ g.setcolor(color.black); //here x=(int)(math.random() * 401); y=(int)(math.random() * 401); } ...
to "refresh" position when mouse over
edit
as @madprogrammer writing below in comment paint() method not best place place logic of application. better place change position listener setting active flag true.
instead of pasting x,y... lines pain() method should rather paste here:
public void mousemoved(mouseevent me) { ... if (xpos > x&& xpos < x+width && ypos > y && ypos < y+height) { active = true; //here x=(int)(math.random() * 401); y=(int)(math.random() * 401); } else ... }
Comments
Post a Comment