title: Java: Ball Collision with Frame
body: <p>Not knowing how to do this is killing me. I currently have a frame with a ball which moves diagonally downwards and right, when it collides with the edge of the frame, it needs to bounce. The bounce part I can work out myself after, what I need help with is the ball knowing when it hits the edge of the frame. </p>
  
  <p>Main:</p>
  
  <pre><code>class ControlledBall extends JPanel {
  private int x = 70;
  private int y = 30;
  private boolean yes = true;
  
  public void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setColor(Color.BLUE);
      Ellipse2D.Double ball = new Ellipse2D.Double(x,y,50,50);
      g2.draw(ball);
      g2.fill(ball);
  }
  public void moveRight(int d) {x = x + d;}
  public void moveDown(int d) {y = y + d;}
  public void gogo() {yes = true;}
  public void nono() {yes = false;}
  
  public static void main(String[] args) {
      JFrame frame = new Viewer();
      frame.setSize(500, 500);
      frame.setTitle("Bouncing Ball");
      frame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
      frame.setVisible(true);
  }
  }
  </code></pre>
  
  <p>Viewer Class:</p>
  
  <pre><code>public class Viewer extends JFrame {
  JButton go = new JButton("GO");
  JButton stop = new JButton("STOP");
  JPanel buttons = new JPanel();
  Timer timer;
  
  ControlledBall cbPanel = new ControlledBall();
  JPanel left = new JPanel();
  JPanel right = new JPanel();
  JPanel top = new JPanel();
  
  
  class gogoListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
          cbPanel.gogo();
          timer.start();
      }
  }
  
  class nonoListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
          cbPanel.nono();
          timer.stop();
      }
  }
  
  class TimerListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
          cbPanel.moveRight(5);
          cbPanel.moveDown(5);
          repaint();
      }
  }
  
  public Viewer() {
      buttons.add(go);
      buttons.add(stop);
      this.add(buttons, BorderLayout.SOUTH);
      this.add(cbPanel, BorderLayout.CENTER);
      this.add(right, BorderLayout.EAST);
      this.add(top, BorderLayout.NORTH);
      this.add(left, BorderLayout.WEST);
  
      timer = new Timer(50, new TimerListener());
      go.addActionListener(new gogoListener());
      stop.addActionListener(new nonoListener());
      timer.start();
      cbPanel.setBorder(BorderFactory.createLineBorder(Color.black));
  }
  
  }
  </code></pre>