SevO
SevO

Reputation: 303

Store instances into an array in java

I am working on a project where I have a bunch of buttons, mostly split into two groups and I would like to work with these groups through an array. Each button is an instance of class Button extends JButton and each instance has its own value (this.value = "..")

The problem is that it seems like array is being filled with previously mentioned instances, but when I try to reach them, it acts like array is filled with nulls.

Button but1, but2, but3;
Button[] buttonNumbers = {but1, but2, but3};

System.out.println(buttonNumbers.length);     // returns 3, so it acts like array IS filled
System.out.println(but1.value);               // prints whatever the value is
System.out.println(buttonNumbers[0].value);    // throws error, element acts like null

Could someone help me out, where is the problem or what am I missing ?
Thank you for every tip or answer!

Upvotes: 0

Views: 66

Answers (1)

Jacob G.
Jacob G.

Reputation: 29680

It doesn't seem like you're initializing each Button! You need to call its constructor for each Button with whatever parameters you defined:

Button but1 = new Button(), but2 = new Button(), but3 = new Button();
Button[] buttonNumbers = {but1, but2, but3};

System.out.println(buttonNumbers.length);     // returns 3, so it acts like array IS filled
System.out.println(but1.value);               // prints whatever the value is
System.out.println(buttonNumbers[0].value);

Upvotes: 3

Related Questions