0

我正在制作一个游戏,您将鼠标悬停在目标单击(射击)上。我想知道如何确定是否单击了 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);

  };
}

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

4

1 回答 1

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
    }
}
于 2012-11-21T18:43:52.767 回答