2012-12-08 70 views
1

我有一個垂直的顏色欄,它有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顏色。爲什麼?

+0

什麼東西要塗在漸變的頂部?如果不是,則在「BufferedImage」中繪製圖像並將其顯示在標籤中。將鼠標監聽器添加到標籤並將顏色直接從圖像中取出。 –

回答

0

我明白了!

我換成這一行:

BufferedImage img = (BufferedImage)this.createImage(getWidth(), getHeight()); 

有了這個:

BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); 
Graphics2D g = img.createGraphics(); 
this.paint(g); 

而現在它完美的作品!

+0

最優秀! –

3

我想我看到了問題。該行

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

返回一個int []對應的RGB顏色。 getPixel方法將您的數組作爲參數 ,但它會返回自己的數組。它從來沒有真正觸及你的數組。你想要做的是這個。

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

應該將方法的返回值存儲在數組中,而不是它的默認值是。

+0

不,沒有任何區別,它仍然包含3個相同的rgb顏色。 –

+0

所以,我寫了'BufferedImage img =(BufferedImage)this.createImage(getWidth(),getHeight());'給一個文件,它是一個灰色的圖像。 –