lhk
lhk

Reputation: 30086

Listen to tab switches on the panels of a JTabbedPane

I've developed a simple Swing GUI to allow the user to edit the data of my application. The UI is rather simple:

But there's a problem: I need to sync the different JPanels.

For example, the data object stores a list of persons and a list of tasks.

Both JPanels are initialized when they are first opened. The components are created and the layout is set. Now the user can start to work with the UI.

  1. He opens the first tab of the JTabbedPane and creates a the first Person.
  2. He opens the second tab. The Components of the second tab are initialized and list the one person that is available. He assigns a task.
  3. He returns to the first tab and creates a second person.
  4. He switches back to the second tab to deal with the new person.

But the second tab and the JPanel it contains have already been initialized. The user will not see the second person, unless the JPanel is updated. I have implemented a custom update method on my JPanel subclass for tab 2. But how do I call it ?

I need the Swing event that is fired on a Component, when it is redrawn.

Upvotes: 0

Views: 271

Answers (1)

Viktor Seifert
Viktor Seifert

Reputation: 636

Actually updating the second panel when the first gets redrawn is bad idea even if you manage to find the event that gets fired. This would cause the second panel to be updated on every redraw of the first panel, regardless of wether the redraw means that the undelying data has changed or not (think about unsaved data).

You should make the data your tabs maipulate Observable (or Subject from Observer Pattern). Then each tab can react to changes in the data instead of changes in other tabs. This will reduce the time of updates to only when it is really needed and also will decouple the tabs from one another.

The data may repesent changes by firing PropertyChangeEvent's. These in turn should trigger Controller actions as suggested by Gilber Le Blanc in the comments.

Upvotes: 1

Related Questions