gpt4 book ai didi

java - 如何延迟动画移动jlabel java swing?

转载 作者:行者123 更新时间:2023-12-01 20:26:10 25 4
gpt4 key购买 nike

我想将一些标签从 x 移动到 y!但我不知道如何拖延!

我尝试过 Thread.sleep 但它不起作用,有人说这是由于阻止 EDT 造成的,但由于我的英语不好,我无法在互联网上自学!请帮我举个例子!谢谢!

这是我的代码:

    public void jump(JLabel x, int y){
x.setLocation(x.getX()+y, 310);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jump(frog3,100);
//i want to delay each jump about 1 second! please give me some example!
jump(fr0g3,-200);

jump(fr0g2,-100);

jump(frog3,200);

jump(frog2,200);

jump(frog1,100);

jump(fr0g3,-200);

jump(fr0g2,-200);

jump(fr0g1,-200);

jump(frog3,100);

jump(frog2,200);

jump(frog1,200);

jump(fr0g2,-100);

jump(fr0g1,-200);

jump(frog1,100);

}

感谢您的阅读!

最佳答案

i cant read english

如果这个答案在文字上很简单,请原谅我

最简单的...

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private JLabel label = new JLabel("Testing");
private int delta = 4;

public TestPane() {
setLayout(null);
label.setSize(label.getPreferredSize());
add(label);
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int x = label.getX() + delta;
if (x + label.getWidth() > getWidth()) {
x = getWidth() - label.getWidth();
delta *= -1;
} else if (x < 0) {
x = 0;
delta *= -1;
}
int y = (getHeight() - label.getHeight()) / 2;
label.setLocation(x, y);
repaint();
}
});
timer.start();
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

}
}

参见How to use Swing Timers了解更多详情。

我不喜欢 null 布局,我不推荐 null 布局,但认为这是一项学校作业,唯一其他可行的解决方案是使用自定义绘画,我很理解为什么会选择这个方向,尽管自定义绘画解决方案通常会更简单。

关于java - 如何延迟动画移动jlabel java swing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43867884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com