java – super. Problems with paintcomponent (g)

This is a clip:

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

The following errors occur when compiling complete code:

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

Why do I receive this error?

If this is my complete code:

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

Solution

You should use qualified super

movingObjects.super.paintComponent(g);

Because when you use this or super in an inner class (in this case: runnable), you will get the inner class If you want to use an external class of an internal class, use qualified this or qualified super

YourOuterClassName.this
YourOuterClassName.super

Qualified super is a term I can't find in JLS. I invented it myself

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>