开发者

Draw Multiple objects in java?

Hey guy's im making a java game where yellow blocks appear randomly across the game screen and you have to collect them. These objects are created from one class and i was wondering if there is a way to draw all of them?

This is the code that spawns them:

package OurGame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;

public class coins extends JPanel implements ActionListener {
Timer t;
coin c;

    public coins() {
        t = new Timer(1000,this);
        t.start();
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println("1 Second");

        Random rx = new Random();
        Random ry = new Random();

        c = new coin(rx.nextInt(640),ry.nextInt(480));
    }

}

and this is the code for the coin itself.

package OurGame;

import java.awt.Image;

import javax.swing.ImageIcon;

public class coin {
Image coin;

int x,y;
        public coin(int x1, int y1) {

            ImageIcon i = new ImageIcon("C:/coin.png");
            coin = i.getImage();

            x = x1;
            y = y1;
        }

        publ开发者_运维知识库ic Image getImage(){
            return coin;
        }

        public int getX(){
            return x;
        }

        public int getY() {
            return y;
        }
}

Would be awesome if you could help.


Why not create an ArrayList of Coin (class names should be capitalized) or ArrayList. Then if you need to add or remove a Coin from the display, you would add or remove it from the ArrayList. Then the paintComponent method could iterate through the array list in a for loop drawing each coin in the loop.

Also, The simplest way to display a Coin would be to put it into an ImageIcon and then use that to set a JLabel's icon.

e.g. with image scaling to make coin smaller and with image filter to change white background to transparent:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Coins extends JPanel implements ActionListener {
   private static final String COIN_URL_PATH = "http://cdn.dailyclipart.net/wp-content/uploads/medium/clipart0273.jpg";
   private static final String COIN_URL_PATH2 = "http://content.scholastic.com/content/media/products/71/0439510171_rgb15_xlg.jpg";
   private static final String COIN_URL_PATH3 = "http://uscoinstoday.com/images/e/130580876887_0.jpg";
   private static final int PAN_WIDTH = 900;
   private static final int PAN_HT = 700;
   protected static final int TRANSPARENT = new Color(255, 255, 255, 0)
         .getRGB();
   private Timer t;
   private BufferedImage coinImage;
   private ImageIcon coinIcon;
   private Random random = new Random();

   public Coins() {
      setLayout(null);
      try {
         coinImage = ImageIO.read(new URL(COIN_URL_PATH));
         double scaleFactor = 0.35;
         BufferedImage destImg = new BufferedImage((int)(coinImage.getWidth() * scaleFactor),
               (int) (coinImage.getHeight() * scaleFactor), BufferedImage.TYPE_INT_ARGB);
         AffineTransform at = AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
         AffineTransformOp ato = new AffineTransformOp(at,
               AffineTransformOp.TYPE_BICUBIC);
         ato.filter(coinImage, destImg);

         ImageFilter whiteToTranspFilter = new RGBImageFilter() {

            @Override
            public int filterRGB(int x, int y, int rgb) {
               Color color = new Color(rgb);
               int colorSum = color.getBlue() + color.getRed() + color.getGreen();
               int maxColorSum = 600;
               if (colorSum > maxColorSum ) {
                  return TRANSPARENT;
               }
               return rgb;
            }
         };
         ImageProducer ip = new FilteredImageSource(destImg.getSource(), whiteToTranspFilter);
         Image destImg2 = Toolkit.getDefaultToolkit().createImage(ip);


         coinIcon = new ImageIcon(destImg2);
         t = new Timer(1000, this);
         t.start();

      } catch (MalformedURLException e) {
         e.printStackTrace();
         System.exit(-1);
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PAN_WIDTH, PAN_HT);
   }

   public void actionPerformed(ActionEvent e) {
      System.out.println("1 Second");

      Coin c = new Coin(random.nextInt(640), random.nextInt(480), coinIcon);
      add(c.getCoinLabel());
      revalidate();
      repaint();
   }

   public static void main(String[] args) {
      Coins coins = new Coins();
      JFrame frame = new JFrame("Coins");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(coins);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

}

class Coin {
   JLabel coinLabel = new JLabel();

   public Coin(int x1, int y1, ImageIcon coinIcon) {
      coinLabel.setIcon(coinIcon);
      coinLabel.setLocation(x1, y1);
      coinLabel.setSize(coinLabel.getPreferredSize());
   }

   public JLabel getCoinLabel() {
      return coinLabel;
   }

}


You have two options:

1) Save a list of all coins and override the paintComponent() method for your JPanel and call rePaint() after a coint is added.

2) Coin could extend some JComponent which provides a paintComponent method; then you could call this.add( ... ) in you JPanel; and this.rePaint().

Some side note:

1) Your Image should be static; otherwise there is an Image for every coin; although it's the same image.

Example code:

package OurGame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.*;

public class coins extends JPanel implements ActionListener {
    private Timer t;
    private ArrayList<Coin> coins = new ArrayList<Coin>();

    public coins() {
        t = new Timer(1000,this);
        t.start();
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println("1 Second");

        Random rx = new Random();
        Random ry = new Random();

        this.coins.add(new Coin(rx.nextInt(640),ry.nextInt(480)));
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        for(Coin coin : this.coins) {
            g.drawImage(coint.getImage(), coin.getX(), coint.getY(), observer);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜