gpt4 book ai didi

java - super.paintComponent(g) 的问题

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:35:57 25 4
gpt4 key购买 nike

这是片段:

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 面板上使用动画,请使用 Swing Timer .

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

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

我建议您先阅读 Custom Painting 上的 Swing 教程以获得更详细的解释和示例。

关于java - super.paintComponent(g) 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6228775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com