简体   繁体   中英

Accessing value of dynamically created controls Java Swing

I working in Java Swing and I am generating a dynamic form with control names opc1_1, opc1_2, opc1_3, opc2_1, opc2_2, etc. How Do I get the value of each one of controls dynamically? I put a very bad example for illustration

for(int i = 1; i < 10; i ++) {
    Control objControl = get("opc1_" + i);
      if(objControl == JComboBox)
        System.out.println(objControl.getSelectedItem().toString());
      else if(objControl == JTextField)
        System.out.println(objControl.getText); 
}

Thanks so much

Use an array/list to store your Control objects, the names of your Control objects in your code aren't important.

Then just iterate through your array/list like you would for any other array/list to get the value of each one of your Control objects.

Also, = is for assignment, == is for comparison, and instanceof is used for checking if an object is a specific type. You generally try and avoid using the instanceof operator in good OO design.

Note that Component has getName() and setName() methods. As you add more and more components to a container, these are your friend. I don't think that Container has a method getComponentNamed(String s), but it's easy to write.

I second Hovercraft's excellent suggestion of using a Map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM