【发布时间】:2014-02-10 10:27:45
【问题描述】:
我试图弄清楚如何为摆动组件设置动画以从 a 点移动到 b 点。这是一个使红色 JPanel 从左向右移动的代码示例:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MovingSquareExample {
private static final JPanel square = new JPanel();
private static int x = 20;
public static void createAndShowGUI(){
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(square);
square.setBounds(20,200,100,100);
square.setBackground(Color.RED);
Timer timer = new Timer(1000/60,new MyActionListener());
timer.start();
frame.setVisible(true);
}
public static class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent arg0) {
square.setLocation(x++, 200);
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
createAndShowGUI();
}
});
}
}
效果很好,只是我看起来有点波涛汹涌。带有可拖动方块的类似示例(请参阅Draggable Components in Java Swing)的运动看起来更平滑,所以我相信应该有一种方法可以让这个看起来更好。任何建议将不胜感激。
【问题讨论】:
-
看起来还不错,只是有点慢。您可以尝试使用
1000/25延迟并增加x增量。请记住,动画是一种幻觉。还要记住,Swing 使用被动渲染引擎,所以当 Swing 决定应该更新时就会发生更新 -
还可以考虑移动一个形状而不是一个组件,对于example; +1 Minimal, Complete, Valid Example。
标签: java swing animation components