Domanda

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. And I want it to stop printing out these rgb-values the moment my mouse exits the jscrollpane.

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.

Thank you for your time.

Solution: I chukked out the MouseListener and implemented the 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.
            }
        });
È stato utile?

Soluzione

You could simply use a MouseMotionListener and the mouseMoved event to achieve the same result without the need for any Threads

Take a look at How to Write a Mouse-Motion Listener for more details

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top