如果执行了操作(例如按下按钮),我如何平滑地移动 JButton。这是我的例子,但它不能正常工作:
public void actionPerformed(ActionEvent event) {
for(int i = 0; i<50; i++){
ww.button.setLocation(ww.button.getLocation().x+1, ww.button.getLocation().y);//ww is a JFrame child
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
执行操作后,我得到 20*50 毫秒的延迟,按钮位置设置为之前的 loc + 50px,没有中间位置。
最佳答案
在使用 Swing 时始终尽量避免使用 Thread
。在您的代码中,它会使主 EDT 线程 hibernate ,这就是您无法查看中间位置的原因。尝试使用 Swing Timer你会得到它按预期工作。看这里:How to Use Swing Timers并尝试使用 Swing workers .
关于java - JButton 在 Action 上的平滑移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15128611/