[英]How do I need to start a background thread using MouseListener?
The idea of my code is that the moment my mouse enters a specific jscrollpane it starts to print out the rgb-values under it. 我的代码的想法是,当我的鼠标进入特定的jscrollpane时,它开始打印出它下面的rgb值。 And I want it to stop printing out these rgb-values the moment my mouse exits the jscrollpane.
我希望它在我的鼠标退出jscrollpane时停止打印出这些rgb值。
try{
String path = "C:\\Users\\Bernard\\Documents\\viking\\map\\provinces.bmp";
Image image = ImageIO.read(new File(path));
ImageIcon icon = new ImageIcon(image);
lblMap = new JLabel(icon);
JPanel jp = new JPanel();
jp.add(lblMap);
provincesPanel.add(jScrollPane1);
jScrollPane1.setViewportView(jp);
jScrollPane1.setAlignmentX(JFrame.RIGHT_ALIGNMENT);
jScrollPane1.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent me) {
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
mapMuis =true;
SwingWorker sw = new SwingWorker<Color, Color>() {
@Override
protected Color doInBackground() {
while (mapMuis==true){
pointer = MouseInfo.getPointerInfo();
point = pointer.getLocation();
color = robot.getPixelColor((int) point.getX(), (int) point.getY());
System.out.println("Color at: " + point.getX() + "," + point.getY() + " is: " + color);
return color;
}
return color;
}
};
}
@Override
public void mouseExited(MouseEvent me) {
mapMuis=false;
}
});
I am however getting no output at all when my mouse enters the jscrollpane. 然而,当我的鼠标进入jscrollpane时,我根本没有输出。
Thank you for your time. 感谢您的时间。
Solution: I chukked out the MouseListener and implemented the MouseMotion: 解决方案:我chlk了MouseListener并实现了MouseMotion:
jScrollPane1.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent me) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void mouseMoved(MouseEvent me) {
pointer = MouseInfo.getPointerInfo();
point = pointer.getLocation();
color = robot.getPixelColor((int) point.getX(), (int) point.getY());
System.out.println("Color at: " + point.getX() + "," + point.getY() + " is: " + color); //To change body of generated methods, choose Tools | Templates.
}
});
You could simply use a MouseMotionListener
and the mouseMoved
event to achieve the same result without the need for any Thread
s 您可以简单地使用
MouseMotionListener
和mouseMoved
事件来实现相同的结果,而无需任何Thread
s
Take a look at How to Write a Mouse-Motion Listener for more details 有关详细信息,请参阅如何编写鼠标 - 运动监听器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.