super.paintComponent(g) 的问题

2023-12-23

这是片段:

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

当我编译完整的代码时,出现以下错误:

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

为什么我会收到此错误?

如果这是我的完整代码:

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

如果您想在 Swing 面板上显示动画,请使用摇摆计时器 http://download.oracle.com/javase/tutorial/uiswing/misc/timer.html.

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

在自定义面板中,您需要设置 setOvalLocation(Point) 等属性。然后,当计时器触发时,您将更新椭圆形位置并在面板上调用重绘。

我建议您首先阅读 Swing 教程定制绘画 http://download.oracle.com/javase/tutorial/uiswing/painting/refining.html以获得更详细的解释和示例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

super.paintComponent(g) 的问题 的相关文章

随机推荐