gpt4 book ai didi

java - 我需要如何使用 MouseListener 启动后台线程?

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

我的代码的想法是,当我的鼠标进入特定的 jscrollpane 时,它​​开始打印出其下的 rgb 值。我希望它在我的鼠标退出 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;
}
});

但是,当我的鼠标进入 jscrollpane 时,我根本没有得到任何输出。

感谢您的宝贵时间。

解决方案:我删除了 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.
}
});

最佳答案

您可以简单地使用 MouseMotionListenermouseMoved 事件来实现相同的结果,而不需要任何 Thread

看看How to Write a Mouse-Motion Listener了解更多详情

关于java - 我需要如何使用 MouseListener 启动后台线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22133356/

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