1

So I've been watching TheChernoProject's 2d game development series in Java, and I'm up to episode 9. I've been understanding everything in the series so far, however I can't seem to wrap my head around the BufferedImage and pixels array.

(link to episode: https://www.youtube.com/watch?v=HwUnMy_pR6A)

I don't understand how the pixels array relates to the BufferedImage object. From what I understand, when you start the program, you create a BuferredImage called image, then you copy the data from each pixel in that image into the array called pixels using

public int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

But at no point do you put the data from pixels back into that image, so how does

g.drawImage(image, 0, 0, getWidth(), getHeight(), null);

draw the data from the pixels array to the screen? I would expect it would just draw a black image.

2 Answers2

0

Your getData() returns a reference to the actual int[], so, this way, when you change its elements you're changing the actual array elements.

Reference: Filthy Rich Clients, Developing Animated and Graphical Effects for Desktop Java(TM), Addison-Wesley, by Chet Haase and Romain Guy, BufferedImage, page 95.

fscherrer
  • 218
  • 3
  • 8
0

Most getters, including the getData()-method in the DataBufferInt class, returns a reference to an Object, which means that when editing the object returned by the getter, you edit the object which the reference returned by the getter points to.

In this case, when calling the getData() method, the reference points to the pixel array which builds up the actual image.

Lets use this code as a simple example:

public class MyClass1
{
    public static int myObject = new MyClass2(278);

    public static MyClass2 getMyObject()
    {
        return myObject;
    }

    class MyClass2
    {
        private int myInt;

        public MyClass2(int myInt)
        {
            this.myInt = myInt;
        }

        public void setMyInt(int newMyInt)
        {
            myInt = newMyInt;
        }
    }
}

Then, this call:

MyClass1.myObject.setMyInt(523);

is equivalent to this call:

MyClass.getMyObject().setMyInt(523);

because MyClass1.getMyObject() returns a reference to myObject, instead of directly addressing myObject with MyClass1.myObject.

Getters are usefull because of many reasons.

For example:

If you allow field access like

shape.x = 90

then you cannot add any logic in future to validate the data.

say if x cannot be less than 100 you cannot do it, however if you had setters like

Some more of them are addressed here.

Community
  • 1
  • 1
Daniel Kvist
  • 3,032
  • 5
  • 26
  • 51