Java 使用计时器设置JPanel(滑入)动画

Java 使用计时器设置JPanel(滑入)动画,java,swing,animation,timer,jpanel,Java,Swing,Animation,Timer,Jpanel,我正在尝试使用我制作的这个类从侧面制作JPanel幻灯片: public class AnimationClass { private int i; private int y; private JPanel panel; private int xTo; private Timer timer; private int xFrom; synchronized void slidePanelInFromRight(JPanel pane

我正在尝试使用我制作的这个类从侧面制作JPanel幻灯片:

public class AnimationClass {

    private int i;
    private int y;
    private JPanel panel;
    private int xTo;
    private Timer timer;
    private int xFrom;

    synchronized void slidePanelInFromRight(JPanel panelInput, int xFromInput, int xToInput, int yInput, int width, int height) {
        this.panel = panelInput;
        this.xFrom = xFromInput;
        this.xTo = xToInput;
        this.y = yInput;

            panel.setSize(width, height);

            timer = new Timer(0, new ActionListener() {
                public void actionPerformed(ActionEvent ae) {

                    for (int i = xFrom; i > xTo; i--) {
                        panel.setLocation(i, y);
                        panel.repaint();
                        i--;

                        timer.stop();
                        timer.setDelay(100);

                        if (i >= xTo) {
                            timer.stop();
                        }
                    }
                    timer.stop();

                }
            });
            timer.start();

    }

}

嗯,我不知道问题出在哪里。我尝试了很多不同的方法,但我似乎无法让它工作。

计时器应该在每个刻度上改变位置,直到它就位。相反,在每个刻度上,您都在运行for next循环,它会阻止EDT,直到循环完成,从而阻止更新UI

使用示例更新

例如

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestAnimatedPane {

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

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

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

    public class TestPane extends JPanel {

        private JPanel panel;

        public TestPane() {
            setLayout(null);
            panel = new JPanel();
            panel.setBackground(Color.RED);
            add(panel);
            Dimension size = getPreferredSize();

            Rectangle from = new Rectangle(size.width, (size.height - 50) / 2, 50, 50);
            Rectangle to = new Rectangle((size.width - 50) / 2, (size.height - 50) / 2, 50, 50);

            Animate animate = new Animate(panel, from, to);
            animate.start();

        }

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

    }

    public static class Animate {

        public static final int RUN_TIME = 2000;

        private JPanel panel;
        private Rectangle from;
        private Rectangle to;

        private long startTime;

        public Animate(JPanel panel, Rectangle from, Rectangle to) {
            this.panel = panel;
            this.from = from;
            this.to = to;
        }

        public void start() {
            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    long duration = System.currentTimeMillis() - startTime;
                    double progress = (double)duration / (double)RUN_TIME;
                    if (progress > 1f) {
                        progress = 1f;
                        ((Timer)e.getSource()).stop();
                    }
                    Rectangle target = calculateProgress(from, to, progress);
                    panel.setBounds(target);
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.setInitialDelay(0);
            startTime = System.currentTimeMillis();
            timer.start();
        }

    }

    public static Rectangle calculateProgress(Rectangle startBounds, Rectangle targetBounds, double progress) {

        Rectangle bounds = new Rectangle();

        if (startBounds != null && targetBounds != null) {

            bounds.setLocation(calculateProgress(startBounds.getLocation(), targetBounds.getLocation(), progress));
            bounds.setSize(calculateProgress(startBounds.getSize(), targetBounds.getSize(), progress));

        }

        return bounds;

    }

    public static Point calculateProgress(Point startPoint, Point targetPoint, double progress) {

        Point point = new Point();

        if (startPoint != null && targetPoint != null) {

            point.x = calculateProgress(startPoint.x, targetPoint.x, progress);
            point.y = calculateProgress(startPoint.y, targetPoint.y, progress);

        }

        return point;

    }

    public static int calculateProgress(int startValue, int endValue, double fraction) {

        int value = 0;
        int distance = endValue - startValue;
        value = (int)Math.round((double)distance * fraction);
        value += startValue;

        return value;

    }

    public static Dimension calculateProgress(Dimension startSize, Dimension targetSize, double progress) {

        Dimension size = new Dimension();

        if (startSize != null && targetSize != null) {

            size.width = calculateProgress(startSize.width, targetSize.width, progress);
            size.height = calculateProgress(startSize.height, targetSize.height, progress);

        }

        return size;

    }
}
更新

我应该在昨晚加上这句话(1岁的人不想睡觉,2个父母不想睡觉,不要再说了…)

动画是一个复杂的主题,尤其是当您开始关注可变速度时(示例是静态的)

不要重新发明轮子,你应该认真考虑一下……/P>
  • -这是一个基本的动画框架,对您可能喜欢如何使用它没有任何假设
  • -与计时框架类似,但也支持内置的基于Swing的组件(通过反射)
这一充分考虑的因素很容易允许以下变化。它利用了
JLayeredPane
中封闭面板的首选尺寸

/**
 * @see https://stackoverflow.com/a/16322007/230513
 * @see https://stackoverflow.com/a/16316345/230513
 */
public class TestPane extends JLayeredPane {

    private static final int WIDE = 200;
    private static final int HIGH = 5 * WIDE / 8; // ~1/phi
    private JPanel panel;

    public TestPane() {
        panel = new JPanel();
        panel.setBackground(Color.RED);
        panel.add(new JButton("Test"));
        add(panel);

        Dimension size = panel.getPreferredSize();
        int half = HIGH / 2 - size.height / 2;
        Rectangle from = new Rectangle(size);
        from.translate(WIDE, half);
        Rectangle to = new Rectangle(size);
        to.translate(0, half);
        panel.setBounds(from);

        Animate animate = new Animate(panel, from, to);
        animate.start();
    }

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


任何事都要以身作则


包测试包;
导入java.awt.Color;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.util.logging.Level;
导入java.util.logging.Logger;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JPanel;
公共类ToggleBtn扩展了JPanel{
JFrame框架;
JPanel小组;
拉贝隆;
拉贝洛夫;
JButton-btn;
整数计数=1;
公共切换btn(){
frame=新的JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
机架立根(500300300300);
frame.setLayout(空);
panelOut=新的JPanel(空);
立根(50,100,120,30);
镶板。背景(颜色。灰色);
框架。添加(面板);
btn=新的JButton(“:”);
btn.立根(0,0,60,30);
添加(btn);
btn.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
startThread();
}
});
labelOn=新的JLabel(“ON”);
拉贝隆后缘(0,0,60,30);
面板。添加(labelOn);
labelOff=新的JLabel(“关闭”);
labelOff.立根(60,0,60,30);
面板。添加(labelOff);
frame.setVisible(true);
}
public void startThread(){
计数++;
新移动().start();
}
公共静态void main(字符串[]args){
新的ToggleBtn();
}
类移动扩展线程{
@凌驾
公开募捐{
如果(计数%2==0){
系统输出打印项次(“如果”);
对于(int i=0;i=0;i--){
试一试{
睡眠(3);
}捕获(中断异常例外){
Logger.getLogger(ToggleBtn.class.getName()).log(Level.SEVERE,null,ex);
}
btn.立根(i,0,60,30);
}
}
}
}
}

OP的代码中存在许多问题。正如MadProrammer所指出的,每个计时器滴答声只能移动一步。这里是一个简单的、经过测试的OPs代码修正,它将JPanel一次移动一个像素,每秒移动25次。请注意以下评论:

synchronized void slidePanelInFromRight(JPanel panelInput, int xFromInput, int xToInput, int yInput, int width, int height) {
this.panel = panelInput;
this.xFrom = xFromInput;
this.xTo = xToInput;
this.y = yInput;

    panel.setSize(width, height);

    // timer runs 25 times per second
    timer = new Timer(40, new ActionListener() {
        public void actionPerformed(ActionEvent ae) {

            // Must 'remember' where we have slid panel to by using instance variable rather than automatic variable
            // Only move one step at a time.
            // No need to restart timer, it continues to run until stopped
            if (xFrom > xTo){
                xFrom = xFrom - 1;
                panel.setLocation(xFrom, y);
                panel.repaint();
            } else {
                timer.stop();
           }

            panel.setLocation(xFrom, y);
            panel.repaint();

        }
    });
    timer.start();

}

您的问题到底是什么,目前表现如何?非常感谢。这是可行的,但我还是想知道运动的速度。如何设置计时器中每个“循环”之间的等待时间?现在,它运行得非常慢(一次1px),但是如果我能减少每次px移动之间的等待时间,那就太完美了。虽然你有点不明白,但我还是不明白。你有很多可以影响速度的变量。第一个是实际计时器的滴答声延迟,我已将其设置为40,这将给您大约25fps。“运行时间”参数确定动画应播放多长时间,设置为2秒。我会在跑步时间玩。动画示例允许每个循环之间的可变延迟,这将为您提供更平滑的动画+1,以获得良好的因数;我无法抗拒。这种方法无法正确同步对
btn
的访问。
synchronized void slidePanelInFromRight(JPanel panelInput, int xFromInput, int xToInput, int yInput, int width, int height) {
this.panel = panelInput;
this.xFrom = xFromInput;
this.xTo = xToInput;
this.y = yInput;

    panel.setSize(width, height);

    // timer runs 25 times per second
    timer = new Timer(40, new ActionListener() {
        public void actionPerformed(ActionEvent ae) {

            // Must 'remember' where we have slid panel to by using instance variable rather than automatic variable
            // Only move one step at a time.
            // No need to restart timer, it continues to run until stopped
            if (xFrom > xTo){
                xFrom = xFrom - 1;
                panel.setLocation(xFrom, y);
                panel.repaint();
            } else {
                timer.stop();
           }

            panel.setLocation(xFrom, y);
            panel.repaint();

        }
    });
    timer.start();

}