我正在尝试制作一个Serpents and Ladders Java应用程序,我想为jLabels移动动画。我希望玩家先水平然后垂直移动,但是当我这样做时它们同时发生。如何使第二个计时器(垂直)等待水平停止。这是简化的代码。
private void mover(javax.swing.JLabel label,boolean inv,boolean y){
ActionListener a = new ActionListener() {
int timesq = 40;
int delta = 1;
int deltax = 0;
@Override
public void actionPerformed(ActionEvent e) {
if (inv){
delta = -1;
}
if (y){
deltax = 1;
}
int x = label.getX() + delta;
int y = label.getY() + deltax;
label.setLocation(x, y);
label.setText(String.valueOf(x));
repaint();
if (--timesq <= 0){
Timer timer = (Timer)e.getSource();
timer.stop();
}
}
};
Timer timer = new Timer(20,a);
timer.start();
}
和触发移动的按钮
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
setLayout(null);
jLabel1.setSize(jLabel1.getPreferredSize());
//add(jLabel1);
//Horizontal movement
int b = 5;
while(b!=0){
mover(jLabel1,false,false);
b--;
}
//Vertical movement
b = 2;
while(b!=0){
mover(jLabel1,false,true);
b--;
}
}
答案 0 :(得分:0)
完成X方向移动后,您需要沿Y方向移动:
private void mover(JLabel label,boolean inv,boolean y){
final int delta = inv ? -1 :1 , deltax = y ? 1: 0, timesq = 40;
ActionListener moveX = new ActionListener() {
int counterX = timesq, counterY = timesq;
@Override
public void actionPerformed(ActionEvent e) {
if(--counterX > 0){ //move at x direction
int x = label.getX() + delta;
label.setLocation(x, label.getY());
label.setText(String.valueOf(x));
}else if(--counterY > 0){ //move at y direction
int y1 = label.getY() + deltax;
label.setLocation(label.getX(), y1);
label.setText(String.valueOf(y1));
}else{
Timer timer = (Timer)e.getSource();
timer.stop();
}
repaint();
}
};
Timer timer = new Timer(20,moveX);
timer.start();
}
(从here复制粘贴运行完整的测试代码)