user1832583
user1832583

Reputation:

Find out if BufferedImage was Clicked

I am making a game where you mouse over a target click (shoot). I would like to know how to figure out if a BufferedImage was clicked.

I have a code like this:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics.*;
import java.awt.Graphics2D.*;
import javax.imageio.*;
import java.io.*;

public class icon_clicked {

public static int mouseX;
public static int mouseY;
public static BufferedImage background;
public static BufferedImage cursor;
public static BufferedImage target;

public static void main(String[] args) {

try {
background = ImageIO.read(new File("background.png"));
}
catch(Exception exc) {
System.err.println("An error has occurred. Error: "+exc);
}

try {
cursor = ImageIO.read(new File("cursor.png"));
}
catch(Exception exc) {
System.err.println("An error has occurred. Error: "+exc);
}

try {
target = ImageIO.read(new File("target.png"));
}
catch(Exception exc) {
System.err.println("An error has occurred. Error: "+exc);
}

JFrame frame = new JFrame("Shooting Range");
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setAlwaysOnTop(false);
frame.setResizable(false);

frame.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
 }
});

frame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
//Solution Code goes here
 }
});


JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {

Graphics2D g2 = (Graphics2D) g;
g2.drawImage(background, 0, 0, null); 
g2.drawImage(cursor, mouseX, mouseY, null); 
g2.drawImage(target, 250, 250, null); 

 }
};

frame.add(panel);

  };
}

I was thinking if there was a click in the area of where the icon was. But I can't seem to figure it out. Could someone please give me a solution? Thanks.

Upvotes: 0

Views: 1789

Answers (1)

FThompson
FThompson

Reputation: 28687

You can check if the clicked point is within the image's rectangle.

public void mouseClicked(MouseEvent me) {
    Point clicked = me.getPoint();
    Rectangle bounds = new Rectangle(250, 250, target.getWidth(), target.getHeight());
    if (bounds.contains(clicked)) {
        // target image was clicked
    }
}

Upvotes: 2

Related Questions