Card Layout Focus
Posted by Rob Camick on October 31, 2008
The CardLayout can be a flexible layout manager to use. Although I think it has two related drawbacks:
- focus is not placed on the Card as it is displayed
- there is no API to determine which Card is currently being displayed
If you could somehow solve the second problem then you could implement the first.
So, I decided to extend the CardLayout to provide some additional functionality. To address the above issues I created the RXCardLayout class with support added for the following methods:
- setRequestFocusOnCard (default true) – when true, the Card will request focus every time it is displayed
- isRequestFocusOnCard – returns the state of the above method
- getCurrentCard – returns the current Card being displayed.
When using the next(…) method of the CardLayout, the displayed Cards will wrap from the last to the first and there is no way to know when you are displaying the last Card. Similiarly, when using the previous(…) method you don’t know when you are displaying the first Card and you will wrap to the last Card. You may wish to control this wrapping process and stop when you reach the last or first card respectively. The following methods will help with this:
- isNextCardAvailable – returns false when currently displaying the last card, true otherwise
- isPreviousCardAvailable – returns false when currently displaying the first card, true otherwise
The key to providing support for all the above methods is the AncestorListener. As a card is added to the layout manager, an AncestorListener is added to the card. We will now be notified whenever a new card is displayed. Since the AncestorListener can only be added to Swing components the component added to the CardLayout must extend from JComponent.
Stay tuned for my next blog entry for further extensions that will make the CardLayout even more programmer friendly.