简体   繁体   中英

Adding components via reflection in swing?

This is probably a very silly way to go about things, but say we had a class with lots of Fields that were components, how would one go about adding them in a for each loop with reflection?

Here is what I've tried so far (though it is obviously doomed to fail):

for(Field bits: this.getClass().getDeclaredFields()){
            try {
                this.add((Component)Class.forName(bits.getName()).newInstance());
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

Each of the fields is not a class so doing the above will not work, but I have defined what they are, and they should exist at runtime.

How should I be doing this?

You try to create a class from a field name, so it won't work.

bits.getName() returns something like "myHelloWorldLabel" and not javax.swing.JLabel.

You can either add the value of the field bits.get(this) or create a new object from the class bits.getDeclaringClass().newInstance() .

I would also add a check that the class extends JComponent.

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