I have two JLabels overlapping each other.
JLabel label = new JLabel();
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));
" label
" is abaixo
of " label1
" and both are inserted in GlassPane
:
layeredPane.add(label, 0, 0);
layeredPane.add(label1, 1, 0);
GlassPane is perfect inside the frame
frame.setGlassPane(layeredPane);
layeredPane.setVisible(true);
frame.setVisible(true);
Only for " label
" (which is below "label1") I created an event on the mouse and when I hover over this label I want it to return the RGB value of its color. p>
ml = new MouseMotionAdapter() {public void mouseMoved(MouseEvent evt) {
Point point = evt.getLocationOnScreen();
Color color = robot.getPixelColor((int)point.getX(),(int)point.getY());
System.out.println(color);
}
};
Since I do not want it to bring any return from label1
, I include:
label1.removeMouseMotionListener(ml);
label.addMouseMotionListener(ml);
The code usually works for the area of the labels . But the mouse still returns the RGB of the colors of label1
over label
, when in fact I want the mouse to return only the RGB value for the color of " label
" which is below " label1
" .
follows the complete 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.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(
"Move the Mouse to Move Duke"));
JLabel label = new JLabel();
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.YELLOW);
frame.setGlassPane(layeredPane);
layeredPane.setVisible(true);
frame.setVisible(true);
ml = new MouseMotionAdapter() {
public void mouseMoved(MouseEvent evt) {
Point point = evt.getLocationOnScreen();
Color color = robot.getPixelColor((int)point.getX(),(int)point.getY());
System.out.println(color);
}
};
label1.removeMouseMotionListener(ml);
label.addMouseMotionListener(ml);
}
}