如何在Java中检测Image类中的点击事件?
我正在通过创建一个简单的游戏来练习学习 Java。在我的简单游戏中,我想使用 AWT 图像类,并且我想单击图像类,它会弹出一个类似警报的对话框,
public class Sample
{
Image img = getImage(getClass().getResource("0.jpg"));
void paint (Graphics g)
{
g.drawImage(img,30,30,this);
}
}
我希望如果我单击该图像,图像将检测到单击事件并显示一个警报对话框。
I'm practicing to learn Java by creating a simple game. In my simple game, I want to use the AWT image class, and I want to click the image class, and it will pop up a dialog box like alert,
public class Sample
{
Image img = getImage(getClass().getResource("0.jpg"));
void paint (Graphics g)
{
g.drawImage(img,30,30,this);
}
}
I want that if I clicked that image the image will detect the click event and it will show an alert dialog box.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最好寻找 Icon/ImageIcon 来显示JLabel 中的图片。然后,您只需添加并重写 MouseListener 中的正确方法用于监听
JLabel
的鼠标点击。It would be better to look for Icon/ImageIcon for displaying a picture in JLabel. Then you need only to add and override the proper method from MouseListener for listening to mouseclick for
JLabel
.前几天写了一个函数:
使用的时候,给出图像的四个点。最后两个点是点击点。
您必须添加一个鼠标侦听器。当事件发生时,您可以使用 isBetween 函数检查单击的点。如果返回 true,则您的图像已被点击。
I wrote a function some days ago:
When you use it, give four points of the image. And the last two points are the clicked points.
You must add a mouselistener. When event action, you check for the clicked point with isBetween function. If it returns true, you image was clicked.
您可以创建一个具有背景图像(您想要的图像)的自定义 JPanel。然后,您可以使用 JPanel 的功能来侦听单击事件。自定义 JPanel 可能是这样的(取自此处) :
有关事件的更多信息,可以看看Oracle教程如何编写组件监听器。
You could create a custom JPanel which has a background image (the image you want). You can then use the JPanel's functionality to listen for click events. A custom JPanel could be something like so (taken from here):
For more information on events, you can take a look at the Oracle tutorial How to Write a Component Listener.