gpt4 book ai didi

java - 获取一个JPanel图形颜色始终是同一种颜色

转载 作者:行者123 更新时间:2023-11-29 05:51:17 26 4
gpt4 key购买 nike

我有一个垂直颜色条,它有 7 种主要颜色,全部组合成一个渐变。然后我将其绘制到 JPanel 中,如下所示:

@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);
}

然后我在同一个类中有一个点击事件,它看起来像这样:

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();
}

img.getRaster().getPixel(evt.getX(), evt.getY(), colors); 总是返回 RGB 颜色:

  • 240
  • 240
  • 240

我可以点击红色、黄色、绿色、青色等任何地方,我总能恢复那些 RGB 颜色。为什么?

最佳答案

我想我看到了问题所在。线路

img.getRaster().getPixel(evt.getX(), evt.getY(), colors);

返回对应于 RGB 颜色的 int[]。 getPixel 方法将您的数组作为一个参数,但它返回自己的数组。它实际上从未接触过您的阵列。你想做的就是这个。

int[] colors = img.getRaster().getPixel(evt.getX(), evt.getY(), new int[3]);

应该将方法的返回值存储在数组中,而不是默认值。

关于java - 获取一个JPanel图形颜色始终是同一种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13773069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com