6

I have some validation that I perform when the user clicks on a tab. If validation == true then allow the tab to show (or to switch to). Right now I am using the StateChanged event to validate. The problem is, when you click on a tab it shows the tabs contents and if validation == false it switches back to previous tab. I do not want it to switch to at all unless validation == true. How do I do this, am I checking for a wrong event? Thank you all

mKorbel
  • 109,525
  • 20
  • 134
  • 319
jadrijan
  • 1,438
  • 4
  • 31
  • 48
  • 4
    The ideal UI/UX way to do this would be to "disable" the tab in question using `pane.setEnabledAt(index, false);` call instead of convoluted logic in `stateChanged` event. – ring bearer Apr 09 '12 at 14:08
  • 3
    You might approach this using a `CardLayout` instead of the `JTabbedPane` - for complete control of when the views change. Using a 'locked tab' `JTabbedPane` would be counter-intuitive to me. – Andrew Thompson Apr 09 '12 at 14:11

2 Answers2

3

You can use the method tab.setEnabledAt(index, false) to disable the tab if validation = false, and tab.setEnabledAt(index, true) to turn it back on when validation = true.

Edit: Disabling a tab will grey it out so the user can't click it in the first place, which means you're going to have to perform the validation check before the user click the tab.

FljpFl0p
  • 348
  • 1
  • 2
  • 10
1

Try override JTabbedPane.setSelectedIndex(int index).

Zecas
  • 647
  • 4
  • 23
  • The cleaner solution may be to override `DefaultSingleSelectionModel.setSelectedIndex(index)` and use the model for JTabbedPane. Yet cleaner solution would be to override `DefaultSingleSelectionModel` to support `VetoableChangeListener`. – xmedeko Nov 13 '12 at 10:09
  • Absolutly agree: xmedeki solution is saffer. – Zecas Nov 14 '12 at 10:59