import java.awt.Color; import java.awt.event.*; import javax.swing.*; public class MoveImagesAlongEllipticalPath implements ActionListener { private JFrame frame; private int frameWidth = 400, frameHeight = 300, numImages = 28; private ImageIcon image = new ImageIcon(getClass().getResource("data_files/apple.png")); private int imageWidth = image.getImage().getWidth(null); private int imageHeight = image.getImage().getHeight(null); private JLabel[] images = new JLabel[numImages]; private int interval = 20, radiusX = 150, radiusY = 50, xPos = 0, yPos = 0, offset = 0; private double angle = 0; public static void main(String[] args) { new MoveImagesAlongEllipticalPath(); } public MoveImagesAlongEllipticalPath() { // Create and set up a JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth, frameHeight); frame.setTitle("Move Images in Elliptical Fashion"); frame.setLocationRelativeTo(null); frame.setResizable(false); // Create an array of 'numImages' Images on JLabels and add to the JFrame for (int i = 0; i < numImages; i++) { images[i] = new JLabel(image); images[i].setSize(imageWidth, imageHeight); images[i].setLocation(-imageWidth, -imageHeight); // Start images off screen frame.add(images[i]); } images[numImages - 1].setVisible(false); // Hide a single wayward image frame.getContentPane().setBackground(Color.BLACK); frame.setVisible(true); // This timer will call the 'actionPerformed' method below when it fires Timer timer = new Timer(interval, this); // 'interval' is in milliseconds timer.start(); } @Override public void actionPerformed(ActionEvent event) { // Using 'offset' ensures that the images do not overlap offset = ++offset % numImages; for (int i = 0; i < numImages; i++) { // Appropriately space and position each image along an elliptical // path; if 'radiusX' and 'radiusY' are the same, a circle is formed angle = i * (Math.PI / 12) + offset; xPos = (int) ((Math.cos(angle) * (radiusX)) + (frameWidth / 2 - 8)); yPos = (int) ((Math.sin(angle) * (radiusY)) + (frameHeight / 2 - 20)); images[i].setLocation(xPos, yPos); } } }