Reputation: 36351
I have a vertical color bar, it has 7 main colors all combined as a gradient. I then take that and paint it to a JPanel
like this:
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
Point2D start = new Point2D.Float(0, 0);
Point2D end = new Point2D.Float(0, h);
float[] dist = {
0.02f,
0.28f,
0.42f,
0.56f,
0.70f,
0.84f,
1.0f
};
Color[] colors = {
Color.red,
Color.magenta,
Color.blue,
Color.cyan,
Color.green,
Color.yellow,
Color.red
};
LinearGradientPaint p = new LinearGradientPaint(start, end, dist, colors);
g2d.setPaint(p);
g2d.fillRect(0, 0, w, h);
}
I then have have a click event in the same class, which looks like this:
public void mouseClick(MouseEvent evt){
BufferedImage img = (BufferedImage)this.createImage(getWidth(), getHeight());
int[] colors = new int[3];
int x = evt.getX();
int y = evt.getY();
img.getRaster().getPixel(evt.getX(), evt.getY(), colors);
ColorPickerDialog.sldColor = new Color(colors[0], colors[1], colors[2]);
getParent().invalidate();
getParent().repaint();
}
The line img.getRaster().getPixel(evt.getX(), evt.getY(), colors);
always returns the RGB colors:
And I can click anywhere, on the Red, Yellow, Green, Cyan, etc. and I always get those RGB colors back. Why?
Upvotes: 1
Views: 1093
Reputation: 36351
I got it!
I replaced this line:
BufferedImage img = (BufferedImage)this.createImage(getWidth(), getHeight());
With this:
BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
this.paint(g);
And now it works perfectly!
Upvotes: 0
Reputation: 462
I think I see the problem. The line
img.getRaster().getPixel(evt.getX(), evt.getY(), colors);
returns an int[] corresponding to the RGB colors. The getPixel method takes in your array as a parameter, but it returns its own array. It never actually touches your array. what you want to do is this.
int[] colors = img.getRaster().getPixel(evt.getX(), evt.getY(), new int[3]);
that should store the return value of the method in your array instead of whatever it's default value is.
Upvotes: 3