0

I'm passing a variable name (JTextField variable name thats already created) into a method as a string, and want to use that string to assign the variable name in that method.

e.g.

  void setpath(String path){

   //textbox1.setText("text");
   path.setText("text");

  }

I can either create several dozen setpath methods with its associated textbox variable name and other stuff, or create one setpath method and use that (what I'm trying to do)

Any way to do this gracefully?

Pengiuns
  • 131
  • 2
  • 9
  • 2
    I am curious as I have seen many questions like this here lately and never understood why: Why do you need this? – RaminS Apr 24 '16 at 01:42
  • I want to avoid writing extra (could be dozens) methods which can be done in one. – Pengiuns Apr 24 '16 at 01:44
  • Possible duplicate of [Assigning variables with dynamic names in Java](http://stackoverflow.com/questions/6729605/assigning-variables-with-dynamic-names-in-java) – Savior Apr 24 '16 at 01:46
  • First of all, there no such type `string`. I think you mean `String` as the type of path passed into your method. Secondly, there is no method named `setText(String)` on the class `String`. So, the code shown is completely invalid. Would it be a safe assumption that your intention is to pass the variable name of a texbox or other component into the method, with which you intend to set some text on? Also, how do you know that object has a `setText()` method? Maybe you should show us some actual code where you need this to help derive a solution. – pczeus Apr 24 '16 at 01:49
  • Yes my bad, I wrote that by hand without the proper notations. and yes you are right. that object has setText() as it is a jTextField. – Pengiuns Apr 24 '16 at 01:51
  • 1
    Why not just pass the object that is of type `jTextField` into the method? You don't have to know 'which' JTextField it is, just that it is one. – pczeus Apr 24 '16 at 01:55
  • TY pczeus, I did not know that was possible (still new). Works like a charm. – Pengiuns Apr 24 '16 at 02:02

1 Answers1

0

Changed argument type String to JTextField and it worked, thanks to pczeus.

 void setpath(JTextField path){

 //textbox1.setText("text");
   path.setText("text");

 }
Pengiuns
  • 131
  • 2
  • 9
  • Please add explanation what was wrong with the askers code and how it should be used instead. Posting only a bunch of code does not always help understanding the proplem. – try-catch-finally Apr 24 '16 at 08:08
  • While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Bono Apr 24 '16 at 10:43