import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Ball extends JFrame {
    
    private int x, y, radius, diameter;
    private JButton move;
    private BallPanel tp;
    private Mover mover;
    
    public Ball() {
        setTitle("ActionListener example");
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        mover = new Mover();
        
        getContentPane().setLayout(new BorderLayout());
        
        tp = new BallPanel();
        getContentPane().add(tp, BorderLayout.CENTER);
        
        JPanel buttons = new JPanel();
        getContentPane().add(buttons, BorderLayout.NORTH);
        
        move = new JButton("Move");
        move.addActionListener(mover);
        buttons.add(move);
        
        radius = 10;
        diameter = radius * 2;
        
        x = diameter;
        y = diameter;
    }
    
    private class Mover implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == move) {
                x += 1;
                y += 1;
                if (x > getWidth()) {x = 0;}
                if (y > getHeight()) {y = 0;}
                tp.repaint();
                
            } else {
                throw new IllegalStateException("This should never happen");
            }
        }
    }
    
    private class BallPanel extends JPanel {
        public BallPanel() {
            super();
            setBackground(Color.white);
        }
        
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.red);
            g.fillOval(x - radius, y - radius, diameter, diameter);
        }
    }
    
    public static void main(String[] args) {
        Ball gui = new Ball();
        gui.setVisible(true);
    }
}
