Search code examples
javaswingjpaneldrawpaintcomponent

How to call draw method outside paintComponent


I have an assignment where I have to draw a circle in a panel and with that circle calculate the reaction time of the user when the circle changes size or color. I've got the paintComponent method. But now I have to call the method for the circles in another class and I don't know how to do that. Can someone please help me with this?

Here is my class where paintComponent is written:

public class ReactionPanel extends JPanel {

boolean setSmallCircle, setInitialCircle;
Color color = new Color (255,0,0); //color  = red
Color c = new Color (255,255,0); //color = yellow
int size;
int x = 250;
int y = x;

public void paintComponent(Graphics g){
  super.paintComponent(g);
  if (setInitialCircle){
    size = 50;
  }
  if (setSmallCircle) {
    size = 50;
  }
  else {
    size = 150;
  }
  g.drawOval(x,y,size,size);
  g.fillOval(x,y,size,size);
}
void setInitialCircle(Graphics g, Color color){
  g.setColor(color);
}
void setSmallCircle(Graphics g, Color c){
  g.setColor(c);
}
void setBigCircle(Graphics g, Color c){
  g.setColor(c);
}
}

Now I would need those (setInitialCircle etc) and call them in my main class ReactionExperiment like so:

void startTest(){
//draw red circle
}

How do I do this? Thanks for the help!


Solution

  • I assume you have two classes, and you'd like to call a public function defined in one from the other. Since the method is not a static method, you'd have to instantiate an object for the class like -

    ReactionPanel obj = new ReactionPanel();
    

    then using this object, you can call any method defined in the first class, like

    obj.paintComponent(g);   // you'll have to define g first though