Search code examples
javajapplet

How do you get a swing button name by string?


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.


Solution

  • 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.