title: Smooth gradient background animation java
body: <p>I'm trying to set an animated gradient background for a JPanel. The effect works, but I would like to get a smooth transition when it starts again. Below is my current implementation. When the xvalue2 reaches a limit set, I swap the colors and start again. </p>
  
  <pre><code>public class GradientAnimation {
  static class GradientPanel extends JPanel {
      private static final long serialVersionUID = -4185583782901846967L;
      private Timer timer;
      private float Xend;
      private final float MAXVALUE = 800f;
      private Color color1 = new Color(128,62,153,255);
      private Color color2 = new Color(192,201,200,255);
  
      GradientPanel() {
          Xend = 0f;
          setOpaque(true);
          ActionListener action = new ActionListener(){
  
              @Override
              public void actionPerformed(ActionEvent evt){
                  if (Xend &lt; MAXVALUE) Xend+=2f;
                  else{
                      Color aux = color1;
                      color1 = color2;
                      color2 = aux;
                      Xend = 0f;
                  }
  
                  revalidate();
                  repaint();
              }   
          };
          timer = new Timer(5, action);
          timer.start();
      }
      @Override
      public void paintComponent(Graphics g) {
          super.paintComponent(g);
  
          Graphics2D g2d = (Graphics2D) g;
          final BufferedImage image = new BufferedImage(
                  getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
          g2d = image.createGraphics();
          GradientPaint prim = new GradientPaint(0f, 0f, color1,
                  Xend, 0f, color2);
  
          g2d.setPaint(prim);
          g2d.fillRect(0, 0, getWidth(), getHeight());
  
          g.drawImage(image, 0, 0, null);
      }
  }
  
  private static void createAndShowUI() {
      try {
          JFrame frame = new JFrame("Gradient Animation");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setLocationRelativeTo(null);
          frame.setResizable(false);
  
          GradientPanel imagePanel = new GradientPanel();
  
          frame.add(imagePanel);
          frame.setSize(400, 400);
          frame.setVisible(true);
      } 
      catch (Exception e) {
          e.printStackTrace();
      }
  }
  
  public static void main(String[] args) {
  
      SwingUtilities.invokeLater(new Runnable() {
          public void run() {
              createAndShowUI();
          }
      });
      }
  }
  </code></pre>
  
  <p>Again, I want to hide the moment that I swap the colors to have a perfect loop of gradient animation. Please let me know if the code looks correct and how could I improve the quality.</p>