import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.Random; public class RandomWalkX extends JPanel implements ActionListener { JButton b = new JButton("Start"); int size = 400; int xpos = size/2, ypos = size/2; int step = 15; Random random = new Random(); Timer timer; boolean still = true; public RandomWalkX () { setBackground(Color.white); add(b); b.addActionListener(new ActionListener() { // the ActionListner public void actionPerformed(ActionEvent e){ // for the button if (still){ // is an anonymous timer.start(); // inner class b.setText("Stop"); } else{ timer.stop(); b.setText("Start"); } still = !still; }}); timer = new Timer(100,this); } public void actionPerformed(ActionEvent e) { // for Timer-driven movement xpos += random.nextInt(step)-step/2; ypos += random.nextInt(step)-step/2; repaint(); } public void paintComponent (Graphics g) { super.paintComponent(g); g.setColor(Color.magenta); g.fillOval(xpos, ypos, 10, 10); } public static void main(String[] u) { JFrame f = new JFrame(); f.setSize(400, 400); f.add(new RandomWalkX()); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }