import javax.swing.*; // J stuff import java.awt.*; // Color import java.awt.event.*; // Timer, KeyListener, ActionListener import java.util.Random; // we don't want to use java.util.* since that package has its own Timer class public class BouncingBallWithWind { public static void main(String[] args) { JFrame frame=new JFrame(); frame.setSize(540,540); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GraphicsPanel gp=new GraphicsPanel(); gp.setFocusable(true); // need to make the panel focusable for KeyListener frame.add(gp); frame.setVisible(true); } public static class GraphicsPanel extends JPanel implements KeyListener, ActionListener // uses both Timer and keyboard input { private BouncingBall2 ball; // We will have a single ball which bounces but we can also affect it with "wind" (keyboard input) private Random gen; // just used in the instantiation of the BouncingBall class public GraphicsPanel() { gen=new Random(); ball=new BouncingBall2(500,500,gen); // instantiate the object addKeyListener(this); // add a KeyListener requiring that we implement 3 methods Timer t=new Timer(10,this); // create a Timer whose ActionListener will be this class t.start(); // start the Timer } public void actionPerformed(ActionEvent e) // Timer generated an ActionEvent, move the ball { ball.move(); repaint(); // and then redraw the Graphics object } public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e){} public void keyPressed(KeyEvent e) // if an arrow is pressed, we will move the ball slightly in the direction of the arrow { if(e.getKeyCode()==KeyEvent.VK_RIGHT) ball.move(5,0); // the values passed to ball.move are the amount of pixels to move the else if(e.getKeyCode()==KeyEvent.VK_LEFT) ball.move(-5,0); // ball in the x and y direction, for instance (5,0) moves it a little to the right else if(e.getKeyCode()==KeyEvent.VK_UP) ball.move(0,-5); else if(e.getKeyCode()==KeyEvent.VK_DOWN) ball.move(0,5); repaint(); // redraw the ball once we have moved it } public void paintComponent(Graphics g) { super.paintComponent(g); // start with a new image g.setColor(Color.white); g.fillRect(0,0,540,540); // fill the background as white ball.draw(g); // have the ball draw itself } } }