0

I have some buttons on named btnA1, btnA2, btnA3, btnB1, btnB2, btnB3, and so forth. I want to know how I can reference to them by combining variable values. For example:

String var1 = "A";
int var2 = 2;
btn[var1+var2].setText("foo"); // <- This line doesn't work. What do I use in place of this one?

Supposedly, the above code will reference to btnA2 but it doesn't work.

2
  • In Java, there aren't viable options for this. I suppose one could try something nasty with Reflection, but a couple of ifs are much cleaner. Commented Nov 17, 2013 at 16:47
  • "What do I use in place of this one?" Reflection. But note that reflection is often the right answer to the wrong question. The right question being 'how to design an app. that can offer X feature to user?'. Commented Nov 17, 2013 at 16:47

3 Answers 3

3

You can't do this in Java. But you can store your buttons in an array.

JButton [] arr = new JButton[6];
//add buttons in the array
btn[1].setText("foo");

Or in a Map :

Map<String, JButton> m = new HashMap<>();
m.put("A2", btnA2)

m.get(var1+var2).setText("foo");
Sign up to request clarification or add additional context in comments.

Comments

0

You can't assign button name dynamically.

 btn[var1+var2].setText("foo");//This is not possible in java

Alternatively design an array of JButton

JButton[] buts=new JButton[]{btnA1, btnA2, btnA3};

for(JButton but: buts){
  but.setText("foo");
}

Comments

0

Best option for you would be a map:

Map<String, JButton> btn = new HashMap<>();
btn.get(var1+var2).setText("foo");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.