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.
Asked
Active
Viewed 1,123 times
0

Andrew Thompson
- 168,117
- 40
- 217
- 433

learner
- 3
- 3
-
It's likely `JButton` – MadProgrammer May 28 '16 at 06:34
-
*"in specific positions"* 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson May 28 '16 at 09:30
3 Answers
2
I you want to have a flexible list of buttons, just declare a List
of JButton
.
List<JButton> listOfButton = new ArrayList<>();

tfosra
- 581
- 5
- 12
-
thanks for your answer but can you please explain how to initialize ArrayList with my buttons named Button1 upto Button100 using 2dArrayList .(my buttons are created in jframe form) please – learner May 28 '16 at 11:48
-
What do you mean by 2dArrayList ? Do you want to create those buttons dynamically ? – tfosra May 28 '16 at 11:54
-
sorry i read ArrayList it is what i want thank u so much,, i was confused by adding 100 buttons with ArrayList mean writing 100 times listOfButton.add(myButtonNumber), for that reason i asked for 2dArrayList. – learner May 28 '16 at 13:52
0
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);
}

learner
- 3
- 3