Hack Forums
[Java] Add alot of buttons to GUI - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Java] Add alot of buttons to GUI (/showthread.php?tid=4121427)



Add alot of buttons to GUI - Pacina - Mar 17, 2014

Hey I want to make a program with a lot of buttons and rather than declaring and adding each one separately I want to use two for loops one for row and one for columns but I'm not sure how do I add them to the pane do I add them inside the for loops for declaring them or a separate loop for the adding??


* - SIM-2015410 - Mar 18, 2014

You can't declare variables dynamically, but you CAN dynamically initialise and add them to the pane in the for loop. You could declare a multidimensional array of JBUTTON for rows and columns, then initialise them in the for loop like this:
Code
JButton[][] buttons = new JButton[6][6];
for(int i = 0; i < 6; I++) {
    for(int j = 0; j < 6; j++) {
      buttons[I][j] = new JButton();
      panel.addComponent(buttons[I][j]);
    }
}



* - skillzforme - Mar 18, 2014

make sure you add the panel where you added the buttons to your JFrame


* - Pacina - Mar 20, 2014

Sorry for the delay replying to this thread been really busy last few days thanks for the posts exactly what I was looking for


* - SIM-2015410 - Mar 20, 2014

(Mar 20, 2014 12:22 AM)Pacina Wrote:  Sorry for the delay replying to this thread been really busy last few days thanks for the posts exactly what I was looking for

Sweet, glad to help out 🙂 PM me if you have any more questions