Title: Loading Images into an array using java
Tags: java
Question: I have a card game that I am developing and need to load card images to the screen. I am using ImageIcon and PaintIcon to Print to image. I want the images to be clickable but I dont know how to do this.
The reason I am using PaintIcon is because I want the images to move with with a click of a button.(stack cards to save space, spread to view them all)
I dont know what to search for or were to get started.
If any one can show me sample code or the right direction that would help.
This is the code I used:
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 &gt; CANVAS_WIDTH - size || x < 0) {
xSpeed = -xSpeed;
if (y &gt; 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();
}
});

Here is the accepted answer: You can add your ImageIcon to a JLabel and then add that label to a panel.
JLabel label = new JLabel(new ImageIcon(path));
panel.add(label);
A better way is to create separate components for each card. Have CardUI extend 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);
Forgot to mention, that now that you have a CardUI class, you can add listeners to it to see if the mouse is on this CardUI.
Comment for this answer: I got the images to apear, I just want to know how can I make a card detect an action event.

Here is another answer: You probably should use a List rather than an array.

Here is another answer: Alright, so you want to see when a user clicks on a card and perform some action. You need to add a MouseListener to your CardUI class.
Here is the sample code I made. Two classes. One is the main panel: Panel, and the other is CardUI which is the UI for cards. The latter displays an image. The former has a null layour manager, otherwise the cards will not be displayed where you want them to, but where the layout manager decides to.
The photo I used is today's google image: http://www.google.ca/logos/2011/Diego_Rivera-2011-res.png and I saved it on 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() &gt;= 0 &amp;&amp; e.getX()<cardPhoto.getWidth()
&amp;&amp; e.getY() &gt;= 0 &amp;&amp; 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) {}

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2011:00:12/07/11', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java>', 'Title': 'Loading Images into an array using java', 'ViewCount': 2172, 'id': 8422347, 'user_AboutMe': '', 'user_AccountId': 376522.0, 'user_DisplayName': 'Tags', 'user_Reputation': 162.0, 'user_Views': 77.0, 'user_id': 728044.0}}