[英]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. 我想知道如何点击BufferedImage。
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. 谢谢。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.