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 > 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();
}
});
}
}