Can we store JButtons in an array?

1.1k Views Asked by At

I am trying to make a small application in Java Swing using JFrame form. I added buttons from palette to panel in specific positions and now want to add these buttons to an array but I don't know the data type used for array that holds these designed buttons. I searched for it but didn't find anything related to my problem. I am new to coding and have very limited knowledge about Java - any help will be greatly appreciated.

3

There are 3 best solutions below

3
tfosra On BEST ANSWER

I you want to have a flexible list of buttons, just declare a List of JButton.

List<JButton> listOfButton = new ArrayList<>();
0
eldo On
JButton[] buttons = new JButton[10];

Just like any other arrays.

0
learner On

Here i am writing the code by using which i added my buttons to arrayList and getting it back.

// creating an ArrayList
ArrayList<JButton> btn = new ArrayList<JButton>();

// adding Buttons to ArrayList
btn.addAll(Arrays.asList(Button1, Button2, Button3,........)); 
//instead of writng btn.add(Button1);btn.add(Button2); and so on, use addAll();

// getting buttons from ArrayList
 for (int i = 0; i < btn.size(); i++){
 btn.get(i);
}