Search code examples
javaawtrobot

Using .getPixelColor with Robot class


Hi there StackOverflow,

I'm currently creating a sort of test maze game in Java and I have made a simple map in Photoshop using only black and white colors. I want my characters to not be able to intersect or pass through these black areas, so I decided to use AWTRobot's ".getPixelColor()" method. However, it seems to not be working. Here is my code:

switch( keyCode1 ) { 
        case KeyEvent.VK_UP:
            thomasY -= 7;
            thomasLabel.setLocation(thomasX, thomasY);
                break;
        case KeyEvent.VK_DOWN:
            System.out.println("Color:  " + robot.getPixelColor(thomasX + frame.getX(),  thomasY+ frame.getY() + thomasLabel.getHeight() + 1));
            if (robot.getPixelColor(thomasX + frame.getX(), thomasY + frame.getY() + thomasLabel.getHeight() + 1) == Color.BLACK)
            {
                System.out.println("At Wall!");
            }
            thomasY += 7;
            thomasLabel.setLocation(thomasX, thomasY);
                break;
        case KeyEvent.VK_LEFT:
           thomasX -= 7;
           thomasLabel.setLocation(thomasX, thomasY);
          thomasLabel.setIcon(imageThomas);
                break;
        case KeyEvent.VK_RIGHT :
            thomasX += 7;
            thomasLabel.setLocation(thomasX, thomasY);
            thomasLabel.setIcon(imageThomasRight);
                break;
    }

This is my code for the movement of my character, and as you can see, whenever the user presses the down arrow it will try and display the Color of the pixel it's at. However, It seems to not register correctly, displaying different colors or the wrong color at it's specific location. Can someone help me do this correctly?


Solution

  • Two problems:

    1) Color.BLACK is defined with an alpha component equal to 255. AWTRobot is reading the screen, and may or may not return an alpha component. You'll have to check that.

    2) The Color returned by AWTRobot is not necessarily interned into the Object that represents an instance of the color "black" internal to the AWT library. You are checking identity; you need to check for equality of the content of the objects.

    Color c1 = new Color(0,0,0);
    Color c2 = new Color(0,0,0);
    
    if (c1 == c2) {
       System.out.println("Will never get here");
    }
    
    if (c1.equals(c2)) {
       System.out.println("The colours (including alpha) are the same.");
    }