Java 能否从类的字段中迭代地向JPanel添加某些组件?

Java 能否从类的字段中迭代地向JPanel添加某些组件?,java,swing,reflection,field,Java,Swing,Reflection,Field,我想使用循环将一种类型的所有组件添加到JPanel中。这是我的第一个想法: public class UI extends JFrame{ private JLabel aLbl; private JLabel bLbl; private Component someOtherComponentA; private Component someOtherComponentB; private JPanel panel; public UI(){

我想使用循环将一种类型的所有组件添加到JPanel中。这是我的第一个想法:

public class UI extends JFrame{
    private JLabel aLbl;
    private JLabel bLbl;
    private Component someOtherComponentA;
    private Component someOtherComponentB;
    private JPanel panel;

    public UI(){
       panel = new JPanel();
       panel.setLayout(new FlowLayout());
       //this is what I am trying to do
       for(JLabel l : Just_the_JLabels)
           panel.add(l);
    }     
}
我在想我可以使用反射来获取JLabel类型的所有字段,但是我不知道如何获取分配给该字段的对象的实例。我有一个很长的组件列表,我认为如果我不复制粘贴panel.add(aLbl)、panel.add(blblbl)、panel.add(cLbl)等,代码中的组件看起来会更好,也不会那么乏味

相反,我打算这样做:

for(Field f : this.getClass().getDeclaredFields()){
    if(f.getType() == JLabel.class)
        //what goes in place of "object associated with field f"
        panel.add(object associated with the field f)
}
---编辑---

解决方案: 公共类UI扩展了JFrame{ private ArrayList=new ArrayList()


只需在
UI
类中为
JLabel
创建getter和setter,现在就可以使用getter方法上的
Method#invoke()
获取对象


我不知道你为什么要使用
反射

还有很多其他的方法。尽量避免反射

for (Field f : this.getClass().getDeclaredFields()) {
    if (f.getType() == JLabel.class) {
        // adjust the method name as per the getter/setter methods name
        Method method = this.getClass().getMethod("get" + f.getName());
        System.out.println(method.getName());
        Object object = method.invoke(this);
        if (object != null) {
            System.out.println(object.getClass().getName());
        }
    }
}

--编辑--

不要使用
反射

private List<JLabel> list = new ArrayList<JLabel>();

// set the label using setter method 
// same for others also
public void setaLbl(JLabel aLbl) {
    if (aLbl != null) {
        // add in the list 
        list.add(aLbl);
    }
    this.aLbl = aLbl;
}

// now simply iterate the list

for(JLabel l : list){
    panel.add(l);
}
private List=new ArrayList();
//使用setter方法设置标签
//其他人也一样
公共无效集合BL(JLabel aLbl){
如果(aLbl!=null){
//添加到列表中
列表。添加(aLbl);
}
this.aLbl=aLbl;
}
//现在只需迭代列表
for(JLabel:list){
小组.添加(l);
}

如果不使用反射,您将如何迭代JLabel字段?如果我可以避免使用反射,我将创建一个
JLabel
数组。如果我创建了一个JLabel数组,我将不得不手动将所有标签添加到数组中。我也可以手动将标签添加到JPanel中,对吗?请告诉我h如何创建标签?
反射
减慢应用速度。
private List<JLabel> list = new ArrayList<JLabel>();

// set the label using setter method 
// same for others also
public void setaLbl(JLabel aLbl) {
    if (aLbl != null) {
        // add in the list 
        list.add(aLbl);
    }
    this.aLbl = aLbl;
}

// now simply iterate the list

for(JLabel l : list){
    panel.add(l);
}