Skip to content
Advertisement

Curious behavior of java.awt.Component, setVisible(), LayoutManager

I was trying to create a GUI and found some curious behavior of java.awt.Component. I wanted to setVisible(true)/setVisible(false) an java.awt.Component by an external Event. But this only works when the to be switched Component was already visible in the first place. Attached, I provided a minimal replica of my problem.

JavaScript

When you remove line testButton.setVisible(false);, testButton is viewable and also switchable in its state of visibility, otherwise not. Does anyone know why? Maybe the layout-manager doesn’t work with invisible components?

EDIT: It seems the layout-manager doesn’t setBounds(...) for invisible components, but why?

Advertisement

Answer

Maybe the layout-manager doesn’t work with invisible components?

Correct, it depends on the rules of the layout manager.

For example the FlowLayout and BoxLayout, ignore invisible components when doing the layout. However, a GridLayout will reserve space.

When using Swing changing a property of a component should automatically invoke the layout manager. So invoking setVisible() should cause a new layout.

However, if layout is not done automatically then you would use code like:

JavaScript

I haven’t used AWT for over a decade now but as I recall AWT is not as smart as Swing so you need to use:

JavaScript

after setting the visible state of the button. At least it works in the MRE you provided.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement