super.paintComponent(g)的问题

Suh*_*pta 3 java graphics user-interface swing

这是片段:

protected void paintComponent(final Graphics g) {

 Runnable r=new Runnable() {

 @Override

  public void run() {
   while(true) {
     super.paintComponent(g);  // <----- line of error
     g.setColor(Color.red);
     g.drawOval(x,y,width,height);
     g.fillOval(x,y,width,height);
     x++;
     y++;
     width++;
     height++;
       if(width==20)
          break;
     try {
        Thread.sleep(100);
     } catch(Exception exc) {
         System.out.println(exc);
       }
   }
  }
};
 Thread moveIt=new Thread(r);
 moveIt.start();
}
Run Code Online (Sandbox Code Playgroud)

编译完整代码时会产生以下错误:

d:\UnderTest>javac mainClass.java
mainClass.java:18: cannot find symbol
     super.paintComponent(g);
          ^
symbol:   method paintComponent(Graphics)
location: class Object
1 error
Run Code Online (Sandbox Code Playgroud)

为什么我会收到此错误?

如果这是我的完整代码:

import java.awt.*;
import javax.swing.*;
import java.lang.Thread;

class movingObjects extends JPanel {
int x=2,y=2,width=10,height=10;

@Override

protected void paintComponent(final Graphics g) {

Runnable r=new Runnable() {

 @Override

  public void run() {
   while(true) {
     super.paintComponent(g);
     g.setColor(Color.red);
     g.drawOval(x,y,width,height);
     g.fillOval(x,y,width,height);
     x++;
     y++;
     width++;
     height++;
       if(width==20)
          break;
     try {
        Thread.sleep(100);
     } catch(Exception exc) {
         System.out.println(exc);
       }
   }
  }
 };
   Thread moveIt=new Thread(r);
    moveIt.start();
    }
   }

class mainClass {

 mainClass() {
 buildGUI();
}

 public void buildGUI() {
 JFrame fr=new JFrame("Moving Objects");
 movingObjects mO=new movingObjects();
 fr.add(mO);
 fr.setVisible(true);
 fr.setSize(400,400); 
 fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

 public static void main(String args[]) {
  new mainClass();
  }
 }  
Run Code Online (Sandbox Code Playgroud)

cam*_*ckr 5

如果你想在Swing面板上动画,那么使用Swing Timer.

您不应该使用while(true)循环,并且该代码绝对不应该是paintComponent()方法的一部分或直接调用paintComponent()方法.

在自定义面板中,您需要设置setOvalLocation(Point)等属性.然后当Timer触发时,您更新椭圆位置并在面板上调用repaint.

我建议你首先阅读自定义绘画的Swing教程,以获得更详细的解释和示例.