What's so special about CardLayout vs manual adding/removal of JPanels?

前端 未结 2 374
盖世英雄少女心
盖世英雄少女心 2020-12-09 11:04

There have been many times on StackOverflow where a user asks a question like this...

I have a main JPanel that contains a child JP

2条回答
  •  鱼传尺愫
    2020-12-09 11:31

    • With CardLayout, it's easier to have loose coupling (though not impossible with roll your own)
    • With CardLayout, the preferredSize of the card-holder is that of the largest card it holds.
    • CardLayout is harder to fark-up, and allows almost trivial contiguous component swapping its next() and prev() methods.
    • You can easily associate the desired component with a constant -- no need to have to create a Map for this purpose as it's already there for you. I've not infrequently used enums for this.
    • No need to remember to call repaint() and revalidate() when swapping components.
    • It's built for and allows for easy re-use of components.

    I can't explain the reason for a down-vote though, unless they're upset you didn't mention the need to remember to call repaint() and revalidate() when swapping components. You'll have to ask the down-voter if they are brave enough to respond.

提交回复
热议问题