Reputation: 1249
I've got a grid which is made of a 2d int array.
It basically contains 00, 01, 02, etc, no need to go into details.
I have a method for extracting the position of the grid which then manipulates the string using a string builder to change it to "jxy" (x = x position in grid, y = y position in grid).
public String getXYstring() {
int x = getX();
int y = getY();
StringBuilder sb = new StringBuilder();
sb.append("j");
sb.append(x);
sb.append(y);
String posXY = sb.toString();
return posXY;
}
So for example if x=1 and y=3 then the method produces: "j13".
All my jLabels are named like this, the grid is 8x8 so they are named: j00, j01, j02 ... j07, j10, j11 etc.
How can I manipulate the label using this generated String?
For example if I wanted to change the jLabel's text using setText how would I do this?
Normally it would be like:
j13.setText("Hello");
However I want the "j13" part to be passed in from my method!
Likewise I don't want this to be restricted to just using setText, I also need to be able to change the colour/background within the label.
I hope this isn't too confusing what I'm trying to achieve!
Upvotes: 0
Views: 465
Reputation: 285405
You can't give variables names by using Strings, but more importantly, you don't want to since the variable name isn't all that important to begin with. Instead you probably want to either use an array of JLabel (1 dimensional or 2 dimensional) and get the label from the array index or create and use a HashMap<String, JLabel>
If you use the HashMap, you will first need to fill it with String/JLabel pairs using its put method, and then you can use the String as a key to extract the JLabel of interest.
myMap.get("j13").setText("hello");
or if in a method,
public void setLabelText(String labelKey, String text) {
myMap.get(labelKey).setText(text);
}
Which you'd call like:
setLabelText("j13", "Hello);
Just be darn sure that all of the key Strings are unique, else this will fail.
Regarding this:
Likewise I don't want this to be restricted to just using setText, I also need to be able to change the colour/background within the label.
I recommend that you don't directly expose class fields outside of the class but rather use public methods that outside classes can call as this will give the class that holds the private fields more complete control over what outside classes can do thus reducing the chance of unwanted side effects.
Upvotes: 2