From your comment on another answer:
I don t want change button name.i want button variable name (in this case it is btn1) change to what string s brings.
Java is not designed that way, if you want to keep a reference for each JButton
you can create an array:
JButton buttonsArray[] = new JButton[5]; //Or any amount of buttons
Then use them like this:
for (int i = 0; i < buttonsArray.length; i++) {
buttonsArray[i] = createButton(text[i]);
}
Where text[i]
is a String
array where you have all the text for your JButton
s
Or probably with an ArrayList
of JButton
:
ArrayList <JButton> buttonsList = new ArrayList <JButton>();
And then use it like:
for (int i = 0; i < text.length; i++) {
JButton button = createButton(text[i]);
buttonList.add(button);
}
Then you can select each button with:
buttonArray[i].setText("Hello"); //Or whatever method you want to call
buttonList.get(i).setText("Hello");
jPanel1.add(buttonsArray[i]);
jPanel1.add(buttonsList.get(i));
Now your createButton()
method should look like this:
public JButton createButton(String s) {
JButton btn1 = new JButton(s);
//Add more code here
return btn1;
}
In this question you can see an similar example using an array of JRadioButton
IMPORTANT NOTE
Finally I need to add this to my answer, don't set location /bounds of each JComponent
manually instead use a proper Layout Manager that does the job for you and Empty Borders to create space between them if needed.
I bet you're using a null
layout and while that might seem like the best and easiest way to create a GUI, the more GUIs you create, you're gonna get more errors due to this and more troubles trying to maintain it.
See: Null layout is evil and Why is it frowned upon to use a null layout in swing?.
I hope that helps