Michael Pate
Michael Pate

Reputation: 99

How to check the color of a pixel in JPanel in Java?

I am trying to write a code in Java that changes the color of a circle based on the location of a click, as well as some if/else statements to change the color of a circle, as well as see if any of the circles at the top of the screen are colored in with a different color other than White. I have the statements that identify the pixel to check, as well as what color to change the circle that the pixel refers to, I just need a bit of code to check what color the pixel is. I am using JPanel as a basis to create the GUI, but I don't know how I would check the color of the pixel.

What I would think the code would look like:

X=e.getX();
Y=e.getY();
if((X,Y)!=(Color.White)){
     Y=Y+100;
     }
else{
     g2.fillOval(X,Y,30,30);
}

the code that I have written already determines which color to fill the circle that the pixel refers to

Upvotes: 0

Views: 1030

Answers (1)

DevilsHnd - 退した
DevilsHnd - 退した

Reputation: 9192

You would need to add a MouseListener for your JPanel in order to get the X & Y mouse pointer location and then with the use of the Robot Class you can get the color of the pixel in that particular location, for example:

jPanel1.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent evt) {
        int x = evt.getX()
        int y = evt.getY();
        try {
            // The the pixel color at location x, y
            Color color = new Robot().getPixelColor(x, y);

            // Display the RGB information of the pixel color in Console Window
            System.out.println("Red   = " + color.getRed());
            System.out.println("Green = " + color.getGreen());
            System.out.println("Blue  = " + color.getBlue());
        }
        catch (AWTException e) {
            e.printStackTrace();
        }
    }
});

There are other ways to accomplish this but, this is the easiest.

Upvotes: 1

Related Questions