javaimagebackground-imagejlabelmousemotionlistener

Get Image color under JLabel


I need to get the pixel´s colors from a image inserted in a JLabel, with MouseMotionListener, and this JLabel is under or behind another JLabel. I know and it´s possible to get a background color behind a JLabel, but what I need is the colors from a image. This is the code:

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;

public class Main extends JFrame {

public static void main(String[] args) throws AWTException
{
    JFrame frame;
    Robot robot;
    JLayeredPane layeredPane;
    MouseMotionListener ml;

    robot = new Robot();
    frame = new JFrame("Pc");
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    layeredPane = new JLayeredPane();
    layeredPane.setPreferredSize(new Dimension(300, 310));
    layeredPane.setBorder(BorderFactory.createTitledBorder(
                                "capture color under the label"));
    JLabel label = new JLabel(new ImageIcon("folder/matiz.jpg"));
    label.setBounds(15, 15, 300, 300);
    label.setOpaque(true);
    label.setBackground(Color.red);

    JLabel label1 = new JLabel();
    label1.setBounds(60, 60, 300, 300);
    label1.setOpaque(true);
    label1.setBackground(new Color(0,0,0,125));

    layeredPane.add(label, 0, 0);
    layeredPane.add(label1, 1, 0);


    frame.setSize(660, 400);

    frame.getContentPane().setBackground(Color.red);
    frame.setGlassPane(layeredPane);
    layeredPane.setVisible(true);
    frame.setVisible(true); 

       ml = new MouseMotionAdapter() {

      public void mouseMoved(MouseEvent evt) {

          JLabel comp = (JLabel) evt.getSource();
          Point point = evt.getLocationOnScreen();

                Color color = robot.getPixelColor((int)point.getX(),  (int)point.getY());
                System.out.println(color);
            }
  };        
            label1.removeMouseMotionListener(ml);
            label.addMouseMotionListener(ml);
    }
}

Solution

  • Everything I did was to remove this code:

    RootPaneContainer comp = (RootPaneContainer) evt.getSource();
    Point point = comp.getRootPane().getLocationOnScreen();
     Color color = robot.getPixelColor((int)point.getX(),(int)point.getY());
    

    and I inserted the code below:

    try{
    BufferedImage img = ImageIO.read(new File("folder/rgb.jpg"));
    int imagem = img.getRGB(evt.getX(), evt.getY());
    Color color = new Color(imagem, true); 
        }
    catch (IOException ex) {
                  Logger.getLogger(Frame1.class.getName()).log(Level.SEVERE, null, ex);
              }