Is it possible to set all JPanes the same background color at once?

poisn :

I'm creating a little game. I know how to set a background color to a JPanel.

pane.setBackground(Color.RED);

My problem is, I've a BorderPane as layout and if I want to place something in the south I need to create a new JPane. Foreach pane I create i need to set the background color again. My Question is, is it possible to set the background color for every pane at once?

GhostCat salutes Monica C. :

Besides the nice idea from Antiossss, you could do one of these two, too:

  • typically, any UI container knows about its children. So you can write some generic code that (probably recursively) fetches the children of some UI component, and if it is a JPanel, set the background
  • probably easier to do: your code simply remembers all JPanels you care about itself

In other words: when you want to treat a number of "things" in similar ways, then easiest solution is to have a field

Set<JPanel> myPanels = new HashSet<>();

in some of your "root" classes, and every time you create a panel ... you add it to that set, so that when you need them you can go:

for(JPanel aPanel : myPanels) { aPanel.setBackground(...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127526&siteId=1