-2

here is the edited code with specified method.

String value =  obj.validateTextFields(txtFields);

public String validateTextFields(JTextField[] txtField){
    String res = "";
        for(JTextField txtFields : txtField) {
               if(txtFields.getText().equals("") ) {
                  JOptionPane.showMessageDialog(null, txtFields.getName() +" is empty!");
                 res +=txtFields.getName()+",";
               }
        }
return res;

value is the names of text fields so how to get the text field by this name.

Noorullah
  • 11
  • 3
  • Your question is quite vague making it difficult to interpret and answer. What do you mean by name? What do you mean by "text field"? What GUI library are you using? Swing? AWT? Android? Other? Please fill in the important details so that we can better understand your code/problem/question. – Hovercraft Full Of Eels Apr 17 '16 at 12:44
  • ok i am using swing library and i have created a method which returns me a string and this string contains the name of JTextFields and now i want to get JTextField by this name. but there is no such a method to access a component by their name. – Noorullah Apr 17 '16 at 12:47
  • You can do it using reflection, but I wouldn't recommend doing so. Look for a validation library - there are lots of them. Spring is a great choice. – duffymo Apr 17 '16 at 12:49
  • I'm not trying to be annoying but only trying to understand. So in that light, please [edit your question](http://stackoverflow.com/posts/36676626/edit), and provide more pertinent code, more background information and greater detail information. Show the method to which you refer. And components don't have "names". Variables do, but that's not a great way to get this information. Better to restructure your program so that information is easily obtainable. – Hovercraft Full Of Eels Apr 17 '16 at 12:49
  • which one the right library for validation. – Noorullah Apr 17 '16 at 12:55
  • `JTextField` inherits the `getName()` and `setName()` methods from `Component`, see [here](https://docs.oracle.com/javase/8/docs/api/java/awt/Component.html#getName--). For information about the usage, see [here](http://stackoverflow.com/questions/227143/what-is-java-awt-component-getname-and-setname-used-for). Please note, that I don't recommend the usage of component names. – Stefan Dollase Apr 17 '16 at 15:52

1 Answers1

1

If you want to associate an object with a String for easy retrieval, one simple way is to use a Map<String, JTextField> with a concrete implementation as a HashMap<String, JTextField>.

Then in your initialization code, you place the components in the map with their associated String using the Map's put(...) method, and later when you want to retrieve it, use the Map's get(...) method.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373