Java秋千:如何平滑动画/移动组件



我正在尝试弄清楚如何使秋千组件从点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();
            }
        });

    }
}

它可以正常工作,只是我看起来有些波动。具有可拖动正方形的类似示例的运动(请参阅Java秋千中的可拖动组件)看起来更加顺畅,因此我相信应该有一种方法可以使这个看起来更好。任何建议将不胜感激。

您正在进入秋千库的棘手区域。但是,没有什么是不可能的。您可以使用计时器创建此类动画,但我真的建议您不要这样做。因此,您可以尽可能最好地移动组件,我建议您使用定时框架库。

但要注意:如果没有学习,就不应该做移动组件。开发了摆动布局,以便将组件按特定顺序放置。如果您操纵尺寸的值和组件的定位值,则您将打破布局的功能,并且您的程序可能以奇怪的方式行事。我有没有使用布局的情况下开发了摇摆应用程序的情况。在操作系统中,我的程序似乎可以正常工作,但是将其移植到其他系统中,一切都混乱了。因此,在启动具有此类自定义的应用程序之前,您需要保持关注并执行许多测试。

这是Javafx技术掌握在我们手中的原因之一。借助这样的技术,我们可以减少内容(将应用程序部署在不同的程序中),并做更多的事情(包括您遇到的麻烦的程序)。考虑迁移到这项技术。因此,您可以看到Javafx可以做什么,下载演示程序集合。如果您对这项技术有兴趣,建议您开始在这里学习。如果您不想下载演示,也可以在互联网上找到展示其工作原理的视频。

如果此替代方案对您来说太费力了,请查看我给您的有关定时框架库的链接。在那里,您会发现Java代码的示例,这些示例在各种挥杆方面制作了流畅的动画,并具有高性能。要学习如何使用此图书馆,我建议您获得由Chet Haase和Romain Guy撰写的肮脏富有客户的书。尽管这本书已过时,并且在库代码中发生了更改,但您可以在图书馆网站上更新。正如我之前说的,下载库,还下载了代码样本。随着时间的流逝,您最终将以最好的方式做自己想做的事情。

希望您能完成想要的工作。祝你好运。:)

这是我使用计时器对JCOMPONENT进行动画的方法。

private void animate(JComponent component, Point newPoint, int frames, int interval) {
    Rectangle compBounds = component.getBounds();
    Point oldPoint = new Point(compBounds.x, compBounds.y),
          animFrame = new Point((newPoint.x - oldPoint.x) / frames,
                                (newPoint.y - oldPoint.y) / frames);
    new Timer(interval, new ActionListener() {
        int currentFrame = 0;
        public void actionPerformed(ActionEvent e) {
            component.setBounds(oldPoint.x + (animFrame.x * currentFrame),
                                oldPoint.y + (animFrame.y * currentFrame),
                                compBounds.width,
                                compBounds.height);
            if (currentFrame != frames)
                currentFrame++;
            else
                ((Timer)e.getSource()).stop();
        }
    }).start();
}

最新更新