找出BufferedImage是否被点击了

时间:2012-11-21 18:40:04

标签: java mouseevent bufferedimage

我正在制作一款游戏,您可以将鼠标移动到目标点击(拍摄)上。我想知道如何点击BufferedImage。

我有这样的代码:

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

  };
}

我在想是否有图标所在区域的点击。但我似乎无法弄明白。有人可以给我一个解决方案吗?感谢。

1 个答案:

答案 0 :(得分:2)

您可以检查点击的点是否在图像的矩形内。

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
    }
}