我把for循环部分直接放在go()方法内执行动画是可以移动的,但是我把for循环放到侦听器ActionListener()内动画就直接略过过程,点击按钮就只会卡一下跳到最后的坐标.
请问一下这个是什么原因,怎么解决呢
package gui;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SimpleAnimation {
JFrame frame;
JButton button;
MyDrawPanel1 drawPanel1;
int x=70;
int y=70;
public static void main (String[] args) {
SimpleAnimation gui=new SimpleAnimation();
gui.go();
}
public void go() {
frame= new JFrame();
button=new JButton("Start");
drawPanel1=new MyDrawPanel1();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel1);
frame.getContentPane().add(BorderLayout.SOUTH,button);
frame.setSize(400,400);
myEvent();
frame.setVisible(true);
/*这一段有问题...
for(int i=0;i<130;i++) {
x++;
y++;
drawPanel1.repaint();
try {
Thread.sleep(50);
}catch(Exception ex) {}
}*/
}
public void myEvent() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
for(int i=0;i<130;i++) {
x++;
y++;
drawPanel1.repaint();
System.out.println("正在执行...");
try {
Thread.sleep(50);
}catch(Exception ex) {}
}
}
});
}
class MyDrawPanel1 extends JPanel{
private static final long serialVersionUID = 1L;
public void paintComponent (Graphics g) {
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
}
}
elsewhere
慕沐9307871
随时随地看视频慕课网APP
相关分类