0

I am trying to write a class to perform a certain action on each component in a JFrame. My idea was to use the method getComponents and then access to the elements of the array that it returns, as shown in the following code

/*window is the JFrame that I am using, while Player1, Player2 ... are all JLabel or JTextField*/

primaryStage.add(Player1);
primaryStage.add(Player2);
primaryStage.add(playerInput);
primaryStage.add(score);
primaryStage.add(timeLeft);
primaryStage.repaint();

Component[] components = window.getComponents();
float scaleFactorX = window.getWidth() / initialWidth;
float scaleFactorY = window.getHeight() / initialHeight;

Arrays.stream(components).forEach( /*performs action on each component*/);

However the array components seems to contain no elements other than the JFrame itself. I have also tried revalidating, but it doesn't work. Any ideas?

Mickael B.
  • 4,755
  • 4
  • 24
  • 48
  • 1
    Maybe have a look at [How to use root panes](https://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html) which has a nice picture of the window hierarchy – MadProgrammer Jan 24 '20 at 09:59
  • JFrame contains only one component: `JRootPane`. Probably you should call `primaryStage.getComponents();`. – Sergiy Medvynskyy Jan 24 '20 at 10:03
  • 2
    Does this answer your question? [How to get all elements inside a JFrame?](https://stackoverflow.com/questions/6495769/how-to-get-all-elements-inside-a-jframe) – jhamon Jan 24 '20 at 10:03
  • Note that `getComponents` is not recursive and doesn't return children's components – jhamon Jan 24 '20 at 10:06

0 Answers0