I can't call the repaint() method in my main method

前端 未结 2 1116
谎友^
谎友^ 2021-01-29 15:53

Everytime I try to call the repaint() method it says a non static method cannot be reference from a static method. Btw, it\'s in the same class as the paintComponent method. I t

相关标签:
2条回答
  • 2021-01-29 16:32

    You can't call it from main() because you can't call non-static functions (repaint()) or use non-static variables inside a static method (main()).

    Instead make the main class implement Runnable and use a thread:

    Thread repaintThread = new Thread("some_name", this); // \
    public void run(){                                    // |
       while(true){                                       // >-Theese shall be in the main class
           repaint();                                     // |
       }                                                  // |
    }                                                     // /
    repaintThread.start();    //this shall be in main()
    
    0 讨论(0)
  • 2021-01-29 16:33

    The main method is static. Your p object is not: it is an instance field of the P class. Try this:

    public static void main(String[] args) throw InterruptedException {
        EventQueue.invokeLater( new Runnable() {
            public void run() {
                P p = new P();
                p.repaint();
            }
        } );
    }
    

    You should always access Swing components from the event dispatch thread, which is why I put it all in a EventQueue invokeLater.

    0 讨论(0)
提交回复
热议问题