jocopa3
jocopa3

Reputation: 796

How do I parse a string to an object's name?

So I have a small amount of objects (10 JLabels) and I want to change their text depending on the users input.

The Initializer for the labels goes like this:

private JLabel j1 = new JLabel();
private JLabel j2 = new JLabel();
private JLabel j3 = new JLabel();
...etc

and continues on to 10.

How do I mass change the text of each JLabel without writing each variable name every time?

I had an idea like below, but I don't know how to access the variable by name from strings.

for(int x=1;x<=10;x++){
  String d = (String) x; //this isn't what d equals, it's example.
  String label = "j"+x;
  label.setText(d); //I know this won't work, but this is what I want to do
}

Is there any way this can be done without errors?

Upvotes: 2

Views: 759

Answers (2)

raddykrish
raddykrish

Reputation: 1866

If you have created the JLabel as an array like JLabel j[10] = new JLabel[10]. Then you can use the for loop to create an instance for each index and then set the text as well.

for(int x=0;x<10;x++){
  j[x] = new JLabel();
  String d = String.valueOf(x); 
  String label = "j"+x;
  j[x].setText(d);
}

Upvotes: 3

sarnold
sarnold

Reputation: 104050

This is an excellent chance to use an array to store your JLabel objects:

private JLabel[] labels = new JLabel[10];

for (int i=0; i<10; i++) {
    labels[i] = new JLabel();
}

/* ... */

for (int i=0; i<10; i++) {
    labels[i].setText("Hello from label " + i);
}

Upvotes: 4

Related Questions