// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;

public class MovingFun extends JFrame {
    public class MyScroller extends JPanel {
        private static final long serialVersionUID = 1L;
        private int w;
        private int h;
        private int r;
        private int x;
        private int y;
        public MyScroller(int w, int h, int r) {
            this.w= w;
            this.h = h;
            this.r = r;
            x = w - 2 * r;
            y = h / 2 - r;
            setPreferredSize(new Dimension(w, h));  
        }
        @Override
        public void paint(Graphics g) {
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, w, h);
            g.setColor(Color.RED);
            g.fillOval(x, y, 2 * r, 2 * r);
        }
        public void move() {
            x--;
            if(x < 0) {
                x = w - 2 * r;
            }
            repaint();
        }
    }
    private static final long serialVersionUID = 1L;
    public MovingFun() {
        MyScroller mys = new MyScroller(800, 100, 25);
        JSlider js = new JSlider(JSlider.HORIZONTAL, 10, 1000, 100);
        JPanel ctl = new JPanel();
        ctl.setLayout(new GridLayout(2, 1));
        ctl.add(new JLabel("Speed:"));
        ctl.add(js);;
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Moving fun");
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(mys, BorderLayout.CENTER);
        getContentPane().add(ctl, BorderLayout.SOUTH);
        pack();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(1000 / js.getValue());
                    } catch (InterruptedException e) {
                    }
                    EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            mys.move();
                        }
                    });
                }
            }
        }).start();
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new MovingFun();
                f.setVisible(true);
            }
        });
    }
}
