Muricula
Muricula

Reputation: 1234

Graphics class in Java

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);    
    }

Upvotes: 1

Views: 410

Answers (2)

trashgod
trashgod

Reputation: 205875

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.

Upvotes: 1

I82Much
I82Much

Reputation: 27326

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);

Upvotes: 3

Related Questions