1

I am trying to graph a function in Java. I know there are plenty of libraries out there for this, but I want to learn how to do Java graphics. I am trying to create a bufferedimage and assign it to a label. Right now I just want to make every other pixel black so I can see that it's working. I will periodically reassign values to the bufferedimage. However, I need a graphics class which is abstract. Do I need to implement my own extension of the graphics class? Is there a better or preferred way to do this? This will likely go for the image observer as well.

Here is my code:

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);    
    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Muricula
  • 1,174
  • 3
  • 9
  • 16
  • 1
    Just curious - why are you using ImageObserver? In my five years of Swing/Java graphics dabbling I've never had to use that class. – I82Much Jan 15 '12 at 06:55
  • for painting in AWT Label is there paint(), but for Swing JComponent (JLabel) is there method paintComponent() – mKorbel Jan 15 '12 at 08:48

2 Answers2

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);
I82Much
  • 26,901
  • 13
  • 88
  • 119
1

You might also like to study these examples that use setRGB(). The first example shows several views in a frame, while the second example offers some insight into how the BufferedImage's ColorModel selects colors.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045