我有一個垂直的顏色欄,它有7個主要顏色全部組合爲一個漸變。然後我採取和它畫到JPanel
這樣的:獲取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);
}
那麼我必須在同一個班級一個click事件,這看起來是這樣的:
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顏色:
而且我可以點擊紅色,黃色,綠色,青色等任何地方,我總是可以獲得那些RGB顏色。爲什麼?
什麼東西要塗在漸變的頂部?如果不是,則在「BufferedImage」中繪製圖像並將其顯示在標籤中。將鼠標監聽器添加到標籤並將顏色直接從圖像中取出。 –