Java:调用实例化实例的方法

时间:2015-02-02 02:41:13

标签: java methods call instance

初学者。

Main.java:

public int foo = 0;

public static void main(String[] args){
   Window f = new Window();
   // do some other stuff
}

public static void incrementFooEverySecond(){
 while(true){
   foo++;
   bar.repaint();    // <- Problem here!
   Thread.sleep(1000);
 }
}    

Window.java:

public class Window extends JFrame {
  public Window(){
    this.setSize(X, Y) //...
    Area bar = new Area();
}}

Area.java:

public class Area extends JPanel implements KeyListener {

method1(){
  super.paint(g);
  g.setColor(Color.RED);
  g.fillRect(foo, foo, B, D);
  this.repaint();
}}

除了标记的1行外,它的工作方式很好。一开始,method1()被执行(我不知道为什么,但这不是问题)。但我需要在Main中的一个函数中调用repaint()的唯一实例中的method1()Area,我无法弄清楚如何。谢谢你的想法。

请注意,我只复制并简化了最重要的代码块。

1 个答案:

答案 0 :(得分:2)

我无法回答为什么method1()被调用,因为您的问题中没有足够的代码来说明原因。

但是,行bar.repaint();是个问题,因为变量bar不在此代码的范围内。您在代码中显示的唯一bar实例是在Window类的构造函数内创建的,并且在该方法结束时超出范围。

要解决此问题,您需要将一个实例变量bar添加到您的Window类中,如下所示:

public class Window extends JFrame {
    private Area bar;

    public Window(){
        this.setSize(X, Y) //...
        bar = new Area();   
    }
}

然后,您需要一种方法来公开重绘功能,例如:

public class Window extends JFrame {
    private Area bar;

    public Window(){
        this.setSize(X, Y) //...
        bar = new Area();   
    }

    public void repaintBar() {
        bar.repaint();
    }
}

现在在Main课程中(Window f与上面Area bar相同的问题):

public class Main {
    static Window f;
    public int foo = 0;

    public static void main(String[] args){
        f = new Window();
        // do some other stuff
    }

    public static void incrementFooEverySecond(){
        while(true){
            foo++;
            f.repaintBar();
            Thread.sleep(1000);
        }
    }
}   
相关问题