我需要使用MouseMotionListener从插入JLabel的图像中获取像素的颜色,并且此JLabel位于另一个JLabel之下或之后。我知道并且可以在JLabel后面获得背景颜色,但我需要的是图像中的颜色。这是代码:
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);
}
}
答案 0 :(得分:0)
我所做的一切都是删除此代码:
RootPaneContainer comp = (RootPaneContainer) evt.getSource();
Point point = comp.getRootPane().getLocationOnScreen();
Color color = robot.getPixelColor((int)point.getX(),(int)point.getY());
我插入了以下代码:
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);
}