如何在paintComponent外调用draw方法

时间:2013-10-14 08:15:46

标签: java swing jpanel draw paintcomponent

我有一个任务,我必须在一个面板中绘制一个圆圈,并用该圆圈计算当圆圈改变大小或颜色时用户的反应时间。我有paintComponent方法。但现在我必须在另一个类中调用圆圈的方法,我不知道该怎么做。有人可以帮我这个吗?

这是我写的paintComponent的类:

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);
}
}

现在我需要那些(setInitialCircle等)并在我的主类ReactionExperiment中调用它们,如下所示:

void startTest(){
//draw red circle
}

我该怎么做? 谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

我相信你想要这个吗?

ReactionPanel reactionPanel = new ReactionPanel();
reactionPanel.setSmallCircle(x, x); 

这段代码实例化了ReactionPanel(它创建了一个新的实例)。因此,您可以在另一个类中使用它的方法。

答案 1 :(得分:0)

我假设您有两个类,并且您希望调用另一个中定义的公共函数。由于该方法不是静态方法,因此您必须为类实例化对象,如 -

ReactionPanel obj = new ReactionPanel();

然后使用此对象,您可以调用第一个类中定义的任何方法,如

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