events - EventListener not working on custom component in Java -


i'm trying draw shape responsive mouse events, thought of extending awt.component can registered event listeners ain't working, although compiles no errors.

import java.awt.component; import java.awt.event.*;  class ball extends component{     public ball(){         this.addmouselistener(new mouseadapter(){             public void mousepressed(mouseevent e){                 // event triggered             }         });     } } 

here's example i'm testing on applet using appletviewer (for learning purpose):

import java.applet.applet; import java.awt.graphics; import java.awt.component; import java.awt.event.*;  public class test extends applet{     ball ball;      public void init(){         ball = new ball();     }      public void paint(graphics g){         ball.paint(g);     } }   class ball extends component{     int x, y;      public ball(){         x = y = 50;         this.addmouselistener(new mouseadapter(){             public void mousepressed(mouseevent e){                 x += 50;                 y += 50;                 repaint();             }         });     }      public void paint(graphics g){             g.filloval(x, y, 25, 25);         } } 

it works when event listener assigned applet in following code:

import java.applet.applet; import java.awt.graphics; import java.awt.component; import java.awt.event.*;  public class test extends applet{     ball ball;      public void init(){         ball = new ball();          this.addmouselistener(new mouseadapter(){             public void mousepressed(mouseevent e){                 ball.x += 50;                 ball.y += 50;                 repaint();             }         });     }       public void paint(graphics g){         ball.paint(g);     } }  class ball extends component{     int x, y;     public ball(){         x = y = 50;     }      public void paint(graphics g){             g.filloval(x, y, 25, 25);         }  } 

this happening because repaint method, when called in ball, repaints ball object, , not applet screen.

when add method in applet, repaints applet screen.

so, have solved problem.... know answer! added answer explanation.

or, need add repaint in both, in ball change position, , in applet repaint it.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -