动画JFrame的位置

时间:2013-01-16 20:26:16

标签: java swing animation jframe

我做了一个简单的JFrame(320 X 64)我在屏幕顶部显示(未修饰(真实);)。是否有一种简单的方法可以在屏幕上方绘制JFrame,将其向下滑动,等待几秒钟,然后重新启动并进行处理?

1 个答案:

答案 0 :(得分:2)

您需要使用Swing TimerJFrame#setLocation(int x,int y)

这是我做的一个小例子:

它只是启动一个Swing Timer来移动未修饰的 JFrame从向下方向开始坐标(在y轴上),直到它到达屏幕的底部通过GraphicsEnvironment#getMaximumWindowBounds()获得。然后开始新的Swing Timer 2500毫秒后,将JFrame移回屏幕顶部而不是dispose() JFrame完成后:

import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class AnimateJFrame {

    private JFrame frame;

    public AnimateJFrame() {
        initComponents();
    }

    private void initComponents() {
        frame = new JFrame() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(300, 300);
            }
        };
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(true);
        frame.pack();
        frame.setVisible(true);

        createAndStartDownwardTimer(frame);
    }

    private void createAndStartDownwardTimer(final JFrame frame) {
        new Timer(25, new AbstractAction() {
            int screenHeight = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
            int y = frame.getY();

            @Override
            public void actionPerformed(ActionEvent ae) {
                if (frame.getY() + frame.getHeight() < screenHeight) {
                    y += 10;
                    frame.setLocation(frame.getX(), y);
                } else {
                    createAndStartUpwardTimer(2500 - 15);//15milis approx latency
                    ((Timer) ae.getSource()).stop();
                }
            }
        }).start();
    }

    private void createAndStartUpwardTimer(int initialDelay) {
        Timer t = new Timer(25, new AbstractAction() {
            int y = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height - frame.getHeight();

            @Override
            public void actionPerformed(ActionEvent ae) {
                if (frame.getY() > 0) {
                    y -= 10;
                    frame.setLocation(frame.getX(), y);
                } else {
                    frame.dispose();
                    ((Timer) ae.getSource()).stop();
                }
            }
        });
        t.setInitialDelay(initialDelay);
        t.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new AnimateJFrame();
            }
        });
    }
}