
how to get image pixels values on mouse click

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
public class GetPixels extends JPanel {
BufferedImage image;
JLabel[] labels;
public GetPixels(BufferedImage image) {
this.image = image;
addMouseMotionListener(mml);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (getWidth() - image.getWidth())/2;
int y = (getHeight() - image.getHeight())/2;
g.drawImage(image, x, y, this);
}
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
private void showPixel(Point p) {
int w = getWidth();
int h = getHeight();
int iw = image.getWidth();
int ih = image.getHeight();
Rectangle rect = new Rectangle(iw, ih);
rect.x = (w - iw)/2;
rect.y = (h - ih)/2;
int x = 0, y = 0;
if(rect.contains(p)) {
x = p.x - rect.x;
y = p.y - rect.y;
}
setLabels(x, y);
}
private void setLabels(int x, int y){
labels[0].setText(String.valueOf(x));
labels[1].setText(String.valueOf(y));
}
private JPanel getLabels() {
labels = new JLabel[2];
for(int i = 0; i < labels.length; i++) {
labels[i] = new JLabel();
}
Dimension d = new Dimension(35, 25);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2,2,2,2);
addComponents("", labels[0], panel, gbc, d, 1.0, 0 );
addComponents("", labels[1], panel, gbc, d, 0, 1.0);
return panel;
}
private void addComponents(String s, JComponent jc, Container c,
GridBagConstraints gbc, Dimension d,
double weightx1, double weightx2) {
gbc.weightx = weightx1;
gbc.anchor = GridBagConstraints.EAST;
c.add(new JLabel(s), gbc);
jc.setPreferredSize(d);
gbc.weightx = weightx2;
gbc.anchor = GridBagConstraints.WEST;
c.add(jc, gbc);
}
public static void main(String[] args) throws IOException {
File file = new File("c:/rose1.jpg");
BufferedImage image = javax.imageio.ImageIO.read(file);
GetPixels test = new GetPixels(image);
JFrame f = new JFrame("GetPixels");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(test));
f.add(test.getLabels(), "Last");
f.setSize(500,400);
f.setLocation(200,200);
f.setVisible(true);
}
private MouseMotionListener mml = new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
showPixel(p);
}
};
}