2012-12-08 2 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); 
} 

I는 다음과 같습니다 같은 클래스의 클릭 이벤트를 가지고 있습니다

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

그리고 빨강, 노랑, 녹색, 청록색 등의 아무 곳이나 클릭 할 수 있으며 항상 그 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); 

은 RGB 색상에 해당하는 int []를 반환합니다. getPixel 메소드는 배열에서 매개 변수를 사용하지만 자체 배열을 반환합니다. 실제로 배열에 닿은 적은 없습니다. 네가하고 싶은 것은 이것이다.

대신 기본값이 아닌 배열에 메서드의 반환 값을 저장해야합니다.

+0

아니, 그 차이가 없었어요, 여전히 3 개의 동일한 RGB 색상이 포함되어 있습니다. –

+0

그래서,'BufferedImage img = (BufferedImage) this.createImage (getWidth(), getHeight());'를 파일에 써서 회색 이미지입니다. –

관련 문제