Java Swing: how to animate / move a component smoothly

I am trying to figure out how to animate a swing component in order to go from point a to point b. Here is an example for a child code that makes a red JPanel move from left to right:


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();

            }
        });


    }

}

It works great, I just look a little weird. The movement for a similar drag-and-drop example (see Draggable Components in Java Swing ) looks much smoother, so I believe there should be a way to make this look better. Any suggestions would be much appreciated.

+4
source share
2 answers

Swing. . ​​ , . , , Timing Framework.

: - , . , . , , , , . , Swing . , , , , . Swing .

, JavaFX . ( ) ( ). . , , JavaFX, Ensemble ( "JavaFX Demos and Samples Downloads" ). .

, , Timing Framework. Java-, Swing- . , , Filthy Rich Client, . , , , - . , , . , , .

, , . .:)

+4

, JComponents .

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();
}
0

All Articles