I am new to Java and I am trying to figure out how to simply add an array of JButton in a JPanel. I've tried using a for loop but it does not work.
Asked
Active
Viewed 41 times
-1
-
4*"I've tried using a for loop but it does not work."* Sure it does. See [Making a robust, resizable Swing Chess GUI](http://stackoverflow.com/q/21142686/418556). Now, as to why **your** attempt is not working, post a [mcve]. – Andrew Thompson Apr 03 '18 at 10:52
1 Answers
0
This should work:
yourJPanel.setLayout(null);
for (int i = 0; i < yourArray.length; i++) {
yourJPanel.add(yourArray[i]);
yourArray.setVisible(true);
yourArray.setBounds(x, y, width, height);
}

FactorX12
- 3
- 6
-
There is no need to use null layout. JPanel itself has FlowLayout. The buttons will display nicely in a linear fashion with JPanel's default layout. – user3437460 Apr 21 '18 at 10:19
-
-
@user3437460 do all the items in the array already have JLabels assigned to them? If it doesn't, then you have to assign a newly declared variable within the for loop, and then add that to the array. – FactorX12 Apr 22 '18 at 05:00