title: Side scrolling background is moving out of frame
body: <p>For a game I need to implement a side scrolling background.
  I have tried this, but my picture is moving out of frame.</p>
  
  <p>What am I doing wrong?</p>
  
  <pre><code>import java.awt.image.BufferedImage;
  import java.awt.*;
  import java.awt.event.*;
  import javax.swing.*;
  import java.net.*;
  import javax.imageio.ImageIO;
  
  public class GameBoard extends JPanel {
  
      private BufferedImage image;
      private int imageCoordX = 0;
  
      public GameBoard() throws Exception {
          setBackground(new Color(0,0,86));
          URL url = new URL("https://i.stack.imgur.com/P59NF.png");
          image = ImageIO.read(url);
          setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
  
          ActionListener animListener = new ActionListener() {
  
              @Override
              public void actionPerformed(ActionEvent e) {
                  imageCoordX = imageCoordX + 10;
                  repaint();
              }
          };
          Timer timer = new Timer(120, animListener);
          timer.start();
      }
  
      @Override
      public void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.drawImage(image, imageCoordX, 0, null);
          System.out.println(imageCoordX);
  
          if (imageCoordX &lt; 0) {
              g.drawImage(image, image.getWidth() + imageCoordX, 0, null); //         
          }
  
          if (imageCoordX &gt; 0) {
              g.drawImage(image, image.getWidth() - imageCoordX, 0, null);
          }
      }
  
      public static void main(String[] args) {
          Runnable r = () -&gt; {
              JFrame f = new JFrame("Animation of Gameboard");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              try {
                  f.add(new GameBoard());
                  f.pack();
                  f.setLocationByPlatform(true);
                  f.setVisible(true);
              } catch (Exception e) {
                  e.printStackTrace();
              }
          };
          SwingUtilities.invokeLater(r);
      }
  }
  </code></pre>