如何使用MouseListener启动后台线程?

时间:2014-03-02 20:56:10

标签: java multithreading swing mouselistener

我的代码的想法是,当我的鼠标进入特定的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时,我根本没有输出。

感谢您的时间。

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

1 个答案:

答案 0 :(得分:2)

您可以简单地使用MouseMotionListenermouseMoved事件来获得相同的结果,而无需任何Thread

请查看How to Write a Mouse-Motion Listener了解详情