问题描述
Code :
public class SimpleAnimation {
int x=70;
int y=70;
public static void main(String[] args) {
SimpleAnimation gui = new SimpleAnimation();
gui.go();
}
public void go()
{
System.out.println("go");
JFrame frame = new JFrame();
frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel mdp = new MyDrawPanel();
frame.getContentPane().add(mdp);
frame.setSize(300,300);
frame.setVisible(true);
System.out.println("go");
for(int i=0;i<130;i++) {
x++;
y++;
mdp.repaint();
System.out.println("go");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
}
class MyDrawPanel extends JPanel{
public void painComponent(Graphics g) {
g.setColor(Color.white);
g.fillRect(0,this.getWidth(),this.getHeight());
g.setColor(Color.green);
g.filloval(x,y,40,40);
}
}
}
查询:
输出应该是填充有白色背景的帧,并在一个圆中倒圆一个小圆圈。但是输出只是一个空框架。会错过什么?我已经将JPanel扩展类用作内部类。有人可以帮助获得所需的输出吗?
***************************************************************************************
解决方法
Swing是单线程的,并且不是线程安全的。
这意味着您不应使用Add the overriding style to your global stylesheet. Scope the selectors so that it only affects the specific elements you need it to.
之类的东西阻塞事件分配线程,也不应从事件分配线程外部更新UI或UI依赖的属性。
您应该通读Concurrency in Swing,这将为您提供更多信息。
下一个问题是您遗忘了Thread.sleep
,应该是painComponent
。在这里使用paintComponent
标记您认为您要覆盖的方法很重要,因为如果父类中不存在该方法,则会生成编译器错误
@Override
,
您的MyDrawPanel不会覆盖paintComponent
方法(您错过了't'),应该是:
@Override
public void paintComponent(Graphics g) {
请注意,(如果有)错字,(可选)@Override
注释会产生编译错误,因此添加它是一个好习惯。