简体   繁体   English

访问动态创建的控件的值Java Swing

[英]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? 我在Java Swing中工作,正在生成带有控件名称opc1_1,opc1_2,opc1_3,opc2_1,opc2_2等的动态表单。如何动态获取每个控件的值? 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. 使用数组/列表来存储您的Control对象,你的名字Control物体在你的代码并不重要。

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. 然后,像遍历其他数组/列表一样遍历数组/列表,即可获取每个Control对象的值。

Also, = is for assignment, == is for comparison, and instanceof is used for checking if an object is a specific type. 同样, =用于分配, ==用于比较, instanceof用于检查对象是否为特定类型。 You generally try and avoid using the instanceof operator in good OO design. 您通常会尝试避免在良好的OO设计中使用instanceof运算符。

Note that Component has getName() and setName() methods. 请注意,Component具有getName()和setName()方法。 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. 我不认为Container有方法getComponentNamed(String s),但它很容易编写。

I second Hovercraft's excellent suggestion of using a Map. 我同意气垫船提出的使用地图的绝妙建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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