gpt4 book ai didi

java - 查明 BufferedImage 是否被点击

转载 作者:行者123 更新时间:2023-12-02 07:26:37 25 4
gpt4 key购买 nike

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

};
}

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

最佳答案

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

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

关于java - 查明 BufferedImage 是否被点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13499918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com