Swing_Frame_Unable可获取动画代码的输出


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, 0, this.getWidth(), this.getHeight());
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}  
}

}

查询:
输出应该是用白色背景填充的框架和圆形中的圆形小圆。但输出只是一个空框架。错过的会是什么?我使用了JPanel扩展类作为内部类。有人能帮助获得所需的产出吗?

***************************************************************************************

Swing是单线程的,并且不是线程安全的。

这意味着您不应该用Thread.sleep之类的东西阻塞事件调度线程,也不应该从事件调度线程外部更新UI或UI所依赖的属性。

您应该通读Swing中的并发,它将为您提供更多信息。

下一个问题是您拼错了painComponent,它应该是paintComponent。这就是使用@Override来标记您认为要覆盖的方法的重要之处,因为如果父类中不存在方法,它将生成编译器错误

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class SimpleAnimation {
int x = 70;
int y = 70;
int tick = 0;
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");
Timer timer = new Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tick++;
if (tick > 129) {
((Timer)e.getSource()).stop();
}
x++;
y++;
mdp.repaint();
}
});
timer.start();
}
class MyDrawPanel extends JPanel {
public MyDrawPanel() {
setBackground(Color.WHITE);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
}
}

MyDrawPanel没有覆盖paintComponent方法(您错过了一个"t"(,这应该是:

@Override
public void paintComponent(Graphics g) {

请注意,(可选(@Override注释会在出现拼写错误的情况下产生编译错误,因此添加它是一个很好的做法

最新更新