How can I concatenate object names with string or integer in java can anyone have an idea.
Button[] digitButtons = new Button[10];
for(int i = 0; i < 10; i ) {
final int buttonInd = i;
Button btn0 i = new Button(Integer.toString(i));
digitButtons[i] = btn0 i;
digitButtons[i].setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
System.out.println("Button pressed " ((Button) e.getSource()).getText());
System.out.println("button clicked " ((Control)e.getSource()).getId());
lastClickedIndex = buttonInd;
}
});
}
CodePudding user response:
Put your buttons in a HashMap<String, Button>
, and this way you could name your buttons and rename them as many times as you want. You cannot rename variables in runtime.
Here is an example:
// this will keep the variables this way: [ "btn01" -> buttonObject1, "btn02" -> buttonObject2 ...]
HashMap<String, Button> buttonHashMap = new HashMap<>();
for(int i = 0; i < 10; i )
{
final int buttonInd = i;
String buttonName = "btn0" i;
Button buttonObject = new Button(Integer.toString(i));
buttonHashMap.put(buttonName, buttonObject);
// The .get(buttonName) gets the specific Button that you need!
buttonHashMap.get(buttonName).setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
System.out.println("Button pressed " ((Button) e.getSource()).getText());
System.out.println("button clicked " ((Control)e.getSource()).getId());
lastClickedIndex = buttonInd;
}
});
}