Why are Frames and JFrames set to invisible by default?
Does anyone know the rational for Java Frames and JFrames being set to invisible by default?
i.e. you have to call myFrameObject.setVisible(true) or you end up with an invisible application interface.
This has been bugging me since you don’t see this in other languages like C# or Objective-C. I was wondering if it was i开发者_Python百科ntended to be a time-saver or if the Java architects were just having a bad day.
Knowing this will help me understand the ultimate answer to life, the universe, and everything.
I always assumed it was so you could populate the window before displaying it. Otherwise you could see a bunch of controls shuffle around as they were added. Probably not a noticeable problem with todays machines + JITs, but in the early days of Java with slower machines and bytecode interpreters in the JVMs it might have made a difference.
It also mimics the way top-level windows work in X11: you create the window, and then later you "map" it (make it visible).
Remember, Swing components are not real components from the OS point of view. Every Swing component needs to be "realized". This is done by invoking the pack() or setVisible() methods. Only at this time will the Swing component be mapped to a peer component of the OS.
And remember when you add components to a visible GUI the components will not appear anyway because you need to invoke the layout manager to layout all the components. So even if the frame was visible automatically, in this case you would still need to invoke frame.validate() to make sure the components are layed out properly.
I think it is a better design to add all the components and then make it visibile once you have finished adding everything to the frame. This way you only layout the components once, not after every component is added. Maybe with other languages that use absolute sizes and positioning this is not a big deal because they don't have the concept of layout managers.
精彩评论