簡體   English   中英

super.paintComponent(g) 的問題

[英]problem with super.paintComponent(g)

這是片段:

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 面板上使用 animation,請使用Swing Timer

您不應該使用 while (true) 循環,並且該代碼絕對不應該是 paintComponent() 方法的一部分或直接調用 paintComponent() 方法。

在您的自定義面板中,您需要設置諸如 setOvalLocation(Point) 之類的屬性。 然后當 Timer 觸發時,您更新橢圓位置並在面板上調用 repaint。

我建議您首先閱讀有關 自定義繪畫的 Swing 教程,以獲得更詳細的解釋和示例。

您應該使用合格的超級。

movingObjects.super.paintComponent(g);

因為,當您在內部 class (在本例中: Runnable )中使用thissuper時,您將獲得內部類。 如果您想從內部 class 使用外部 class,請使用Qualified This或 Qualified Super。

YourOuterClassName.this
YourOuterClassName.super

合格的超級是我在JLS中找不到的術語,是我自己發明的。

因為Runnable沒有paintComponent()方法。 這是使用匿名內部類的缺點之一,它很難看到當前上下文是什么,但在你的情況下,上下文是run()方法,因此super是指你的匿名內部 class 的超類,這是Runnable

如果要從內部 class 引用外部 class 的超類,則應使用movingObjects.super.paintComponent()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM