我把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);
}
}
}
1 回答
已采纳
慕沐9307871
TA贡献27条经验 获得超9个赞
按钮点击事件如果没完成,整个窗口属于阻塞状态。所以如果点击后要处理的操作需要长时间完成,建议用线程封装。
public void myEvent() { button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { new Thread(){ public void run(){ for(int i=0;i<130;i++) { x++; y++; drawPanel1.repaint(); System.out.println("正在执行..."); try { Thread.sleep(50); }catch(Exception ex) {} } } }.start(); } }); }
添加回答
举报
0/150
提交
取消