0

I am trying to create a certain amount of buttons that is equal to the amount of files in a folder. I'm pretty sure this is done through a for loop, although I do not know how to set the unique locations per button, because I couldn't set the location the save or it would just have many buttons in the same spot. Because there could be many files in the folder, using an if statement for each number wouldn't work and would be a tedious process. Would the for loop be creating a new button each iteration? If so, how could I set each location differently? Are there any other ways to do this? I know how to create a button, but I don't know how to set the unique location of each button. (Preferably the y part)

for (int i = 0; i <= numberOfFiles; i++) {
    // Create new button?

}

I am looking to create the same amount of buttons as a certain amount of files in a folder.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Bo0ked61
  • 57
  • 9
  • Does this answer your question? [making a button - java](https://stackoverflow.com/questions/15347293/making-a-button-java) –  Jul 29 '21 at 17:15
  • Not exactly, because I am looking to create the same amount of buttons as a certain amount of files in a folder. – Bo0ked61 Jul 29 '21 at 17:16

1 Answers1

1

Yes, you got it right. Inside your for loop instantiate your new button and add the new button to your user-interface. See this related Question.

for ( int i = 0; i <= numberOfFiles; i++ ) 
{
    JButton button = new JButton( "whatever" );
    myUi.add( button ) ;
}

A shorter way to write that loop, if you do not need a count:

for ( File file : files ) 
{
    JButton button = new JButton( "whatever" );
    myUi.add( button ) ;
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • How could I set a unique location for each creation of a button? It wouldn't do much if all the buttons were in the same spot... – Bo0ked61 Jul 29 '21 at 17:40
  • 1
    You use a layout manager to arrange the buttons. Time for you to **read a tutorial**. Here is [one for Swing](https://docs.oracle.com/javase/tutorial/uiswing/TOC.html) and [one for JavaFX](https://openjfx.io/openjfx-docs/). – Basil Bourque Jul 29 '21 at 17:46
  • Thank you I figured it out! I used a layout manager and it worked perfect. – Bo0ked61 Jul 29 '21 at 22:45