Java 如何将鼠标侦听器添加到包含图像的 JLabel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18359650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to add mouse listener to JLabel which contain image
提问by Java Curious ?
I have added an image to a Jlabel
and I want to add mouse listener to it.
I don't know to add a mouse listener to the Jlabel
that contains the image.
我已经向 a 添加了一个图像Jlabel
,我想向它添加鼠标侦听器。我不知道在Jlabel
包含图像的 中添加鼠标侦听器。
So anyone who knows how to implement this please tell me.
所以任何知道如何实现这一点的人请告诉我。
I want to add a mousedragged listener to the JLabel
.
When the user drags it, it should work.
我想向JLabel
. 当用户拖动它时,它应该可以工作。
MouseHandler mk = new MouseHandler();
JLabel label = new JLabel();
label.addMouseListener(mk);
I have implemented a listener in the class that extends mouse adapter.
我在扩展鼠标适配器的类中实现了一个监听器。
采纳答案by misserandety
You can try :
你可以试试 :
JLabel nameLabel = new JLabel("Name:");
nameLabel.addMouseMotionListener(new MouseMotionAdapter() {
//override the method
public void mouseDragged(MouseEvent arg0) {
// to do .........................
}
});
thats the way I understand your question.
这就是我理解你的问题的方式。
But I guess this can help you too : Drag and move a picture inside a JLabel with mouseclick
但我想这也可以帮助您: 使用鼠标单击在 JLabel 中拖动和移动图片
回答by Dodd10x
You are adding your mouse adapter as a mouse listener (which handles click, enter, exit, pressed, released). You want to add it as a mouse motions listener if you want to handle drag and move events.
您将鼠标适配器添加为鼠标侦听器(处理单击、输入、退出、按下、释放)。如果您想处理拖动和移动事件,您希望将其添加为鼠标动作侦听器。
回答by Abhishek
You can do following:
您可以执行以下操作:
ImageIcon icon = new ImageIcon("C:/image.jpg"); //Path to the image
JLabel label = new JLabel(icon); //add image to the label
label.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
You can add the actions to the above methods as required.
您可以根据需要将操作添加到上述方法中。