1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
   | package Animation;
 
public class Animation {
  public static void main(String[] args) {
 
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new BackgroundPane());
        frame.pack();
        frame.setVisible(true);
      }
}
 
class BackgroundPane extends JPanel {
  private BufferedImage bg;
  private int yOffset = 0;
  private int yDelta = 1;
 
  public BackgroundPane() {
    try {
      bg = ImageIO.read(new File("src/images.png"));
    } catch (Exception ex) {
      ex.printStackTrace();
    }
 
    Timer timer = new Timer(10, new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        yOffset += yDelta;
        if (yOffset > getHeight()) {
          yOffset = 0;
        }
       repaint();
      }
    });
    timer.start();
  }
 
  @Override
  public Dimension getPreferredSize() {
    return new Dimension(300,300);
  }
 
  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
 
    int xPos = (getWidth() - bg.getWidth()) / 2;
    int yPos = yOffset;
 
    yPos = yOffset;
    while (yPos < getHeight()) {
      g2d.drawImage(bg, xPos, yPos, this);
      yPos += bg.getHeight();
 
    }
 
    g2d.dispose();
  }
} | 
Partager