1

I'm trying to define a swing button label by using a string and then converting the string to a button name and then using the name to set the label.

Somehow it doesn't work, and I've tried to use getClass(); and Class.forName();

Here is my custom class where I try to change a button label by putting in the button name as a string;

public void zet(String scl){
Class c = scl.getClass();
//Class c = Class.forName(scl);
if (beurt) {
  c.setLabel("X");
  beurt = false;
} // end of if
else{
  c.setLabel("O");
  beurt = true;
}}

Can somebody please help me with this? Many thanks in advance.

Lolslayer
  • 63
  • 8
  • Why do you want to do it this way? What are you trying to accomplish? Can you explain a bit more please? – hamena314 Jun 09 '16 at 07:27
  • I wanted to make a class that would automatically change a few things of buttons, The only thing you should define when calling the class is the name of the button itself, that would be saved in a string, the I wanted to convert the string in a way that I can use it to alter the label of the specified button – Lolslayer Jun 09 '16 at 14:49

1 Answers1

1

You can't do this.

Java reflection and "class for name" does not allow you to do that. There is no component around that keeps track of those JButtons that you created "via new()" before and would allow you to find one just by its "name".

If you need such kind of functionality, you have to implement your own "registry", something like:

Map<String, JComponent> componentsByName = new HashMap<>();
... then you add components like
componentsByName.put("button-1", someJButton); ...
... and later on, 
( componentsByName.get("button-1") ).setLabel() ...

In other words: especially when you are newbie, don't assume that you just need to hear the name of a "concept" in order to be able to use it. Instead, you should always assume that things might be more complicated, and that you should spent some serious time to read documentation about the concept you heard about to understand if it is really what you need; and if so, how to use it.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Thanks for the comment, but you didn't have to lecture me though, I know it isn't long, but I've spent an hour trying to find a way how to do this, after trying to get it working multiple times I just didn't get it to work, don't think that I'm coming here every time something doesn't work, because I don't, I only do this when I'm really stuck – Lolslayer Jun 09 '16 at 13:24
  • Didn't want to be rude. But this is a very experience that I have made here: one should not assume that "names" alone (like "forName()") tell you what the thing is going to do for you. – GhostCat Jun 09 '16 at 15:05