Paul Taylor
Paul Taylor

Reputation: 13190

How to check and prevent changing tab on JTabbedPane?

I have tabbed options panel, I want to verify as user tabs to a different panel. I added a ChangeListener but this only fires after they have changed tab, I want to check before the tab changes and prevent the tab change if any of the information in invalid.

Upvotes: 0

Views: 610

Answers (1)

Holger
Holger

Reputation: 298103

Like all Swing components, the JTabbedPane does not control its state by itself. It delegates to a model which is responsible for it. You can set your own model via JTabbedPane.setModel(). If you don’t want to implement the SingleSelectionModel interface completely on your own you can just create a subclass of DefaultSingleSelectionModel and override the setSelectedIndex(int index) method and decide whether to pass the request to the superclass implementation based on your condition.

This is the solution when you want the check the condition in time (i.e. when the tab has been clicked), maybe because checking it in advance is too expensive. Otherwise, if you know ahead of time that a certain tab is not allowed you can simply invoke JTabbedPane.setEnabledAt(int, boolean)

Upvotes: 3

Related Questions