Java,在JApplet中为静止图像设置动画

时间:2015-11-07 01:07:18

标签: java swing animation japplet

我正在完成一项任务,而且我基本上完成了这项任务,它只是一个简单的程序来创建一个图像地图并为热点添加一些音频,我还剩下几天了尝试和#34;动画"图片。

它是汽车仪表板的图片,当用户点击点火器时,我将看看是否有办法让图像震动一秒钟。我曾尝试在这里和谷歌上搜索,但每次我搜索时都会收到来自90年代applet的文章而不是JApplet的文章。

如果你可以指出我正确的方向如何#34;动画"图像,甚至是可能有教程的地方,我都很感激!

这是我的代码,如果你想看看我正在谈论的内容,并且可以帮助我。

public class ImageMap extends JApplet implements MouseListener{
   private Image pic;
   private Container contentPane;
   private JLabel directions;
   private Rectangle horn;
   private Rectangle vent;
   private Rectangle doorLocksUpper;
   private Rectangle window;
   private Rectangle radio;
   private Rectangle ignition;
   private int x, y;
   private AudioClip hornSound, airSound, radioClip, lockSound1, lockSound2, ignitionSound;

public void init() {        
    pic = getImage(getCodeBase(), "CarDash.jpg");
    horn = new Rectangle(250, 142, 105,104);
    vent = new Rectangle(514, 159, 204, 72);
    doorLocksUpper = new Rectangle(80, 167, 104, 58);
    window = new Rectangle(122, 243, 88, 55);
    radio = new Rectangle(514, 234, 176, 171);
    ignition = new Rectangle(465, 217, 42, 43);

    directions = new JLabel("CLICK ON: Horn, Door Locks, Air Vents, Radio & Ignition Push Start");

    //Create components
    contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout());
    contentPane.add(directions, BorderLayout.NORTH);
    contentPane.addMouseListener(this);
}


//Display image on applet window
public void paint(Graphics g) {
    g.drawImage(pic, 0, 40, this);

}

public void mouseClicked(MouseEvent me) {
    //Play horn clip when car horn is clicked.
    if(horn.contains(me.getX(), me.getY())) {
        play(getCodeBase(), "HornSound.wav");
    }
    if(vent.contains(me.getX(), me.getY())) {
        play(getCodeBase(), "AirVent.wav");
    }
    if(ignition.contains(me.getX(), me.getY())) {
        play(getCodeBase(), "Ignition.wav");
    }
    if(doorLocksUpper.contains(me.getX(), me.getY())) {
        play(getCodeBase(), "DoorLocks.wav");
    }
    if(radio.contains(me.getX(), me.getY())) {
        play(getCodeBase(), "BrownSugar.mid");
    }
    if(window.contains(me.getX(), me.getY())) {
        play(getCodeBase(), "Window.wav");
    }
}
public void mouseReleased(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
public void mousePressed(MouseEvent me) {}
}

1 个答案:

答案 0 :(得分:2)

这是一个非常快速有用的提示,不要直接绘制到顶级容器(如applet)。它将您陷入一个单一的用例中,并不总是使其更容易修改或重复使用。

相反,首先使用JPanel之类的东西作为主要容器,然后将其添加到您喜欢的内容,applet,窗口,其他容器中。

虽然你可以通过多种方式在Swing中进行动画制作,但最简单(也是最安全的)之一就是使用Swing Timer

此示例仅使用Swing Timer,设置为每16ms更新一次(对于我的捕获软件快速更新:P),单击面板时启动。计时器只是更新一个在正值和负值之间隔离的偏移值。 Timer使用LocalTime计算Timer在一秒钟后停止运行的时间长度

Shake it up baby

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalTime;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ShakeAnimation {

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

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

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new ShakePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ShakePane extends JPanel {

        private Timer timer;
        private LocalTime startTime;
        private int xOffset = 0;
        private int delta = 8;

        private BufferedImage img;

        public ShakePane() {
            try {
                img = ImageIO.read(getClass().getResource("Duke-Thumbs.jpg"));
            } catch (IOException exp) {
                exp.printStackTrace();
            }
            timer = new Timer(16, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Duration duration = Duration.between(startTime, LocalTime.now());
                    if (duration.getSeconds() >= 1) {
                        timer.stop();
                        xOffset = 0;
                    } else {
                        xOffset *= -1;
                    }
                    repaint();
                }
            });
            addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    if (!timer.isRunning()) {
                        xOffset = delta;
                        startTime = LocalTime.now();
                        timer.start();
                    }
                }

            });
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                int x = ((getWidth() - img.getWidth()) / 2) + xOffset;
                int y = (getHeight() - img.getHeight()) / 2;
                g2d.drawImage(img, x, y, this);
                g2d.dispose();
            }
        }

    }

}

有关详细信息,请参阅How to use Swing Timers