2012-01-15 67 views
1

我正在嘗試繪製Java中的函數。我知道這裏有很多圖書館,但我想學習如何做Java圖形。我正在嘗試創建一個bufferedimage並將其分配給一個標籤。現在我只想讓其他所有像素變成黑色,這樣我就可以看到它正在工作。我會定期爲bufferedimage重新分配值。但是,我需要一個抽象的圖形類。我是否需要實現自己的圖形類的擴展? 有沒有更好或更喜歡的方式來做到這一點? 這也可能用於圖像觀察者。Java中的圖形類

這裏是我的代碼:

static BufferedImage I = new BufferedImage(X, Y, BufferedImage.TYPE_INT_RGB); 
public static void main(String args[]){ 
     JLabel label = new JLabel(new ImageIcon(I)); 
     panel.add(label); 
painter(I); 
//edited to remove various declarations 
} 
public static void painter(BufferedImage b){ 
     for(int x = 0; x<b.getWidth(); x+=2){ 
      for(int y = 0; y<b.getHeight(); y+=2){ 
       b.setRGB(x,y, 000000); 


      } 
      paint(g, iobs); 
     } 

public void paint(Graphics g, ImageObserver iobs) 
    { 
     //ImageObserver iobs 
     g.drawImage(I, 0, 0, iobs);// iobs);  
    } 
+1

只是好奇 - 爲什麼你使用ImageObserver?在我五年的Swing/Java圖形涉獵中,我從來不需要使用那個類。 – I82Much 2012-01-15 06:55:06

+0

用於在AWT Label中繪製是否有paint(),但是用於Swing JComponent(JLabel)的方法是paintComponent() – mKorbel 2012-01-15 08:48:51

回答

3
BufferedImage a = ...; 
// In fact, this is a Graphics2D but it's safe to use it 
// as a Graphics since that's the super class 
Graphics g = a.createGraphics(); 

// now you can draw into the buffered image - here's a rect in upper left corner. 
g.drawRect(0, 0, a.getWidth()/2, a.getHeight()/2); 
1

你可能還喜歡研究這些例子中使用setRGB()。第一個example在一個框架中顯示了幾個視圖,而第二個example提供了一些有關BufferedImageColorModel如何選擇顏色的信息。