使用java将图像加载到数组中

时间:2011-12-07 20:52:23

标签: java

我正在开发一款卡片游戏,需要将卡片图像加载到屏幕上。我正在使用ImageIcon和PaintIcon来打印图像。我希望图像可以点击,但我不知道如何做到这一点。

我使用PaintIcon的原因是因为我希望只需点击一下按钮即可移动图像。(堆叠卡以节省空间,传播以查看所有图像)

我不知道要搜索什么或者要开始使用。

如果有人可以向我展示样本代码或正确的方向,那将有所帮助。

这是我使用的代码:

public class CustomGraphicsDemo2 extends JFrame {

  // Define constances
  private static final int CANVAS_WIDTH = 640;
  private static final int CANVAS_HEIGHT = 480;

  //Array of image cards


  //Handle for the custom drawing panel
  private DrawCanvas canvas;

  private ImageIcon card1, card2, card3,card4;

  //Attributes of Drawing object
  private int x = 100;      // x and y position
  private int y = 100;
  private int size = 50;    
  private int xSpeed = 3;   // moving speed in x and y directions
  private int ySpeed = 5;

  //Constructor to create the UI components
 public CustomGraphicsDemo2() {
  canvas = new DrawCanvas();
  canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
  this.setContentPane(canvas);
  this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  this.pack();
  this.setTitle("Custom Graphics Demo");
  this.setVisible(true);

  // Refresh the display at regular interval.
  // Run the display refresh code in its own thread.
  Thread updateThread = new Thread() {
     public void run() {
        while (true) {
           update();   // update the (x, y) position
           repaint();  // Refresh the JFrame, callback paintComponent()
           try {
              // Delay and give other thread a chance to run
              Thread.sleep(50);  // milliseconds
           } catch (InterruptedException ex) {}
        }
     }
  };
   updateThread.start();   // callback run()
 }

 // Update the (x, y) position of the graphical object
   public void update() {
   x += xSpeed;
   y += ySpeed;
   if (x > CANVAS_WIDTH - size || x < 0) {
     xSpeed = -xSpeed;
   }
   if (y > CANVAS_HEIGHT - size || y < 0) {
      ySpeed = -ySpeed;
   }
}


   //Custom drawing canvas (designed as inner class).
   class DrawCanvas extends JPanel {
   // Custom drawing codes
   @Override
   public void paintComponent(Graphics g) {

      super.paintComponent(g);
      setBackground(Color.BLACK);
      g.setColor(Color.BLUE);
      g.fillOval(x, y, size, size);  // draw a circle


      //cards being drawn
      card1 = new ImageIcon("Uno Cards/Blue/ EIGHT.png");
      card1.paintIcon(this, g, 50, 100);

      card2 = new ImageIcon("Uno Cards/Blue/FIVE.png");
      card2.paintIcon(this, g, 100, 100);

      card3 = new ImageIcon("Uno Cards/Blue/NINE.png");
      card3.paintIcon(this, g, 150, 100);

      card4 = new ImageIcon("Uno Cards/Blue/EIGHT.png");
      card4.paintIcon(this, g, x, y);

      //Graphics2D g2 = (Graphics2D) g; //we use this for drawing later. 
      //g2.fill(new drawImage());
      //g2.fill(new Rectangle2D.Double(10,y,size,size));

    }
 }

  // main program
  public static void main(String[] args) {

   SwingUtilities.invokeLater(new Runnable() {
      public void run() {
         new CustomGraphicsDemo2();
       }
    });
  }
 }

3 个答案:

答案 0 :(得分:2)

您可以将ImageIcon添加到JLabel,然后将该标签添加到面板。

JLabel label = new JLabel(new ImageIcon(path));
panel.add(label);

更好的方法是为每张卡创建单独的组件。让CardUI扩展JComponent

class CardUI extends JComponent {
    //... class members ...

    public CardUI(BufferedImage cardPhoto){
        this.cardPhoto= cardPhoto;
    }

    void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(cardPhoto, x, y, this);
    }
}

编辑: 忘了提一下,既然你有一个CardUI类,你可以添加一个监听器来查看它是否在这个CardUI上。

答案 1 :(得分:1)

你可能应该使用List而不是数组。

答案 2 :(得分:1)

好吧,所以你想看看用户点击卡片并执行某些操作的时间。您需要将一个MouseListener添加到CardUI类。

以下是我制作的示例代码。两节课。一个是主面板:Panel,另一个是CardUI,它是卡片的UI。后者显示图像。前者有一个空的业余经理,否则卡片不会显示在你想要的地方,而是布局经理决定的地方。

我使用的照片是今天的谷歌图片:http://www.google.ca/logos/2011/Diego_Rivera-2011-res.png我把它保存在C:\ im.png

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Panel extends JPanel {

    private CardUI cui1, cui2;

    public Panel(BufferedImage cardPhoto){
        cui1= new CardUI(cardPhoto,10,10);
        cui2= new CardUI(cardPhoto,10,60);

        setLayout(null);//make sure you dont have a layout manager

        this.add(cui1);
        this.add(cui2);
    }


    public static void main(String[] args) {
        BufferedImage cardPhoto;
        Panel panel;

        try {
            cardPhoto= ImageIO.read(new File("c:/im.png"));
            panel = new Panel(cardPhoto);

            JFrame f = new JFrame("Card UI Demo");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(250,250);


            f.getContentPane().add(panel);
            f.setVisible(true);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}


import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;
import javax.swing.border.LineBorder;

/**
 * @author eamocanu
 * This class is not thread safe
 */
public class CardUI extends JComponent implements MouseListener {
    private BufferedImage cardPhoto;
    private static int id=0;
    private int myId; //so to name components for the purpose of this sample

    public CardUI(BufferedImage cardPhoto, int x, int y) {
        this.cardPhoto= cardPhoto;
        myId= ++id;

        setBorder(LineBorder.createGrayLineBorder());
        setMaximumSize(new Dimension(cardPhoto.getWidth(),cardPhoto.getHeight()));
        setMinimumSize(new Dimension(cardPhoto.getWidth(),cardPhoto.getHeight()));
            //FYI: setting preferred size has different effects on various systems
        setPreferredSize(new Dimension(cardPhoto.getWidth(),cardPhoto.getHeight()));

        //move this component to the right location on the screen
        //Note: this works if there is no layout manager to its parent container
        setBounds(x, y, cardPhoto.getWidth(), cardPhoto.getHeight());

        this.addMouseListener(this);
    }


    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(cardPhoto, 0, 0, this);
    }


    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getX() >= 0 && e.getX()<cardPhoto.getWidth()
                && e.getY() >= 0 && e.getY()<cardPhoto.getHeight()){
            System.out.println("Clicked Card: "+myId);
        }
    }


    @Override
    public void mouseEntered(MouseEvent e) {
        System.out.println("mouse entered "+myId);
    }


    @Override
    public void mouseExited(MouseEvent arg0) {
        System.out.println("mouse exited"+myId);        
    }


    @Override
    public void mousePressed(MouseEvent arg0) {}


    @Override
    public void mouseReleased(MouseEvent arg0) {}

}
相关问题