I'm building a Java swing application that uses JSplitPanes. Sometimes when I'm testing my application, the JSplitPanes jump to their default position after certain actions. I can move the divider to any location, but the certain action always causes the divider to jump to the same position it was when the program first opened.
My code is too large to show samples of, so I would like to know in general what could cause this.
One thing I have tried is taking out a call to revalidate(), and that did stop the JSplitPanes from jumping. However, it caused another system (one that makes our menus dynamic) to stop working altogether.
Is there a way to stop the JSplitPanes from jumping without breaking the dynamic menu system?
So I was unable to find the source of the problem, but I did find a work around that works quite well:
splitPane.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY,
new java.beans.PropertyChangeListener() {
@Override
public void propertyChange(java.beans.PropertyChangeEvent pce) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
Component left = splitPane.getLeftComponent();
Component right = splitPane.getRightComponent();
left.setPreferredSize(left.getSize());
right.setPreferredSize(right.getSize());
}
});
}
});
Basically, when the JSplitPane gets resized, it sets the preferred sizes of its two inner components, which it then uses to determine the divider location. The invoke later call was also necessary, as it didn't work without it.
I was going to do a SSCCE, but I came up with this idea while thinking about how to go about it, and tested it and it worked.