0

I have a package, which contains a lot of java swing components all of them extend a range of different JSwing components. In a separate file I want to access all of these components and put them into an ArrayList?

I can do it in any way i want but i do not see how i could get it from looping through every file and I also do not know how to do it if I import it into an ArrayList dynamically.

For example:

-MyComponentsPackage
  -Component1 (This extends JLabel)
  -Component2 (This extends JButton)
  -...

in another file I need to do:

private List<JComponent> = new ArrayList<JComponent>();

I want to be able to loop through every object and add them to a JPanel:

for (Component componentInPackage : allComponentsInPackage) {
    myPanel.add(componentInPackage);
}
  • Try reflection? – chriptus13 Jul 03 '20 at 21:51
  • You wrote in your question: _I want to be able to loop through every object and add them to a JPanel_ Why do you need to do this? You will need to create an instance of each `JComponent` and add it to the `JPanel`. – Abra Jul 04 '20 at 10:27
  • @Abra I have hundreds of components and I thought there would be a more efficient way that writing that many lines of code for it. – user13861763 Jul 04 '20 at 11:51
  • So you want a `JPanel` that contains hundreds of components? – Abra Jul 04 '20 at 14:17

1 Answers1

1

I'd suggest checking out this post: Can you find all classes in a package using reflection?

It provides a solution that you could use, but also goes into an explanation.

genius42
  • 243
  • 1
  • 6
  • How would I access the actual object to a JPanel? – user13861763 Jul 04 '20 at 10:05
  • If you have managed to retrieve all relevant classes you can create instances of them using `Class#newInstance()´ (https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#newInstance) – genius42 Jul 04 '20 at 12:26