La creación de infinidad de objetos en JPanel y atraerlos a través paintComponent en Java

Gipsy Kings:

Tengo un dilema, la forma de realizar la aplicación. Tengo JPanel con un ancho de 288 y 512 de altura, resulta que he creado dos objetos (imágenes) y los trajeron a través paintComponent usando coordenadas

 drawImage (Image1,288,128,this) ;
 drawImage (Image2, 288, 384, this);

. Están disminuyendo simultáneamente en el eje X y cuando alcanza x = 144, nuevas imágenes (las mismas) deben elaborarse en las coordenadas (x = 288, y = (int) Math.random () * 512) 'y comenzar decremento así como los primeros todavía deben decrementa. Y este proceso debe ser interminable. Cada nuevos objetos que llegan x = 144 deben construir nuevas. Intenté crear ArrayList con la adición de coordenadas en ella

ArrayList arrayX = new ArrayList(); 
arrayX.add(288)
arrayY.add((int) Math.random()* 512 )

y luego extraer valores a través

array.get()

Pero eso fue sin éxito. sierra de vídeo I donde el hombre lo hizo uso de JavaScript a través de la matriz

var position = []
position = ({
X : 288
Y : 256
 })

Y luego implementado a través del lazo como esto

 function draw() {

 for (int i = 0; i < position.length; i++ ){
 cvs.drawImage(Image1,position[i].x , position[i].y)
 cvs.drawImage(Image2,position[i].x , position[i].y + 50)

 position [i] .x - -;
 if(position[i].x == 128)
 position.push({
 X : 288
 Y : Math.floor(Math.random()*512 })
 })
 }
 }

No sé cómo hacer esto en Java. Puede ser que debería usar una matriz demasiado para mantener las variables con las coordenadas, o arrayList pero en forma diferente. Ayudame por favor . Gracias por adelantado

c0der:

Mi respuesta está completamente basado en la respuesta de MadProgrammer (Un tutorial completo en realidad).
Por lo que leo en el mensaje: "Todos los nuevos objetos alcanzando x = 144 debe construir otras nuevas", creo que la aplicación deseada es ligeramente diferente:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class ImageAnimator {

    public ImageAnimator() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Testing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new AnimationPane());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

    public static class Drawable {

        private int x;
        private final int y;
        private static final Image image = image();

        //construct with a random y value
        public Drawable(int x) {
            this(x, -1);
        }

        public Drawable(int x, int y) {
            this.x = x;
            this.y =  y < 0 ? (int) (Math.random() * (512 - 20)) : y;
        }

        public int getX() { return x;  }

        public int getY() { return y; }

        public void update() {  x--; }

        public Image getImage(){  return image; }

        public static Image image() {

            URL url = null;
            try {
                url = new URL("https://dl1.cbsistatic.com/i/r/2017/09/24/b2320b25-27f3-4059-938c-9ee4d4e5cadf/thumbnail/32x32/707de8365496c85e90c975cec8278ff5/iconimg241979.png");
                return ImageIO.read(url);

            } catch ( IOException ex) {
                ex.printStackTrace();
                return null;
            }
        }
    }

    public class AnimationPane extends JPanel {

        private final List<Drawable> drawables;
        private static final int W = 288, H = 512, CYCLE_TIME = 5;

        public AnimationPane() {
            drawables = new ArrayList<>(2);
            drawables.add(new Drawable(W, H/4));
            drawables.add(new Drawable(W, 3*H/4));

            Timer timer = new Timer(CYCLE_TIME, e ->  animate());
            timer.start();
        }

        private void animate() {

          for (Drawable drawable : new ArrayList<>(drawables)) {

              drawable.update();
              if(drawable.getX() == W/2) {
                  drawables.add(new Drawable(W)); //random Y
              }
              if(drawable.getX() <= 0) {
                  drawables.remove(drawable);
              }
          }
          repaint();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(W, H);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (Drawable drawable : drawables ) {
                g.drawImage(drawable.getImage(),drawable.getX(), drawable.getY(), null);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->new ImageAnimator());
    }
}

introducir descripción de la imagen aquí

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=204349&siteId=1
Recomendado
Clasificación