import java.awt.Graphics; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JComponent; import javax.swing.Timer; class BouncingBall extends JComponent implements ActionListener { private int x = 0; private int y = 0; private int size = 50; private int horizontalStep = 1; private int verticalStep = 1; private int delay = 2; private Color color = Color.BLUE; private BouncingBall() { // set canvas to an initial size, // otherwise it won't show up this.setSize(1, 1); // create timer to redraw the circle // after the delay time has expired Timer timer = new Timer(delay, this); // start the timer timer.start(); } public void actionPerformed(ActionEvent e) { // boundaries int west = 0; int south = this.getHeight() - 1 - size; int east = this.getWidth() - 1 - size; int north = 0; // increment step for x coordinate, // check for boundaries and invert // direction if necessary this.x = this.x + this.horizontalStep; if (this.x < west || this.x > east) { this.horizontalStep = this.horizontalStep * -1; this.x = this.x + 2 * this.horizontalStep; } // dito for y coordinate this.y = this.y + this.verticalStep; if (this.y < north || this.y > south) { this.verticalStep = this.verticalStep * -1; this.y = this.y + 2 * this.verticalStep; } // fancy gimmick for changing the color // when the circle hits a boundary if (this.x == west || this.x == east || this.y == north || this.y == south) { this.color = color.equals(Color.BLUE) ? Color.RED : Color.BLUE; } // call for repainting the canvas this.repaint(); } @Override public void paintComponent(Graphics g) { // fit canvas size to window size this.setSize(this.getParent().getSize()); // fill background g.setColor(Color.WHITE); g.fillRect(0, 0, this.getWidth(), this.getHeight()); // draw circle shape g.setColor(this.color); g.fillOval(x, y, size, size); } public static void main(String[] args) { JFrame window = new JFrame("My Bouncing Ball"); window.setLocation(100, 100); window.setSize(800, 600); window.getContentPane().add(new BouncingBall()); window.setVisible(true); } }