Jason B
Jason B

Reputation: 1

Can you iteratively add only certain components to a JPanel from the fields of a class?

I want to add all the components of one type to a JPanel using a loop. This is my first thought:

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);
    }     
}

I was thinking I could use reflection to obtain all the fields of the JLabel type, but then I couldn't figure out how to obtain the instance of the object assigned to the field. I have a long list of components and thought that it would look nicer in the code and be less tedious if I didn't copy paste panel.add(aLbl), panel.add(bLbl), panel.add(cLbl), etc.

Instead I was going to do something like this:

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)
}

---edit---

Solution: public class UI extends JFrame{ private ArrayList = new ArrayList();

    public UI(){
        init();
    }

    public void setLbl(JLabel l){
        list.add(l)
    }

    private init(){
        setLabel(new JLabel("labelName"); //do this for each label

        for(JLabel label : list)
            panel.add(label);
    }
}

Upvotes: 0

Views: 116

Answers (1)

Braj
Braj

Reputation: 46891

Just create the getter & setter in your UI class for JLabel an now you can get the object using Method#invoke() on getter methods.


I don't know why are you using reflection?

There are lots of other ways. Try to avoid reflection at all.

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());
        }
    }
}

--EDIT--

Try in the way without using reflection

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);
}

Upvotes: 0

Related Questions