Java and JScrollPane: where to call setPreferredSize?
I am using a JScrollPane
and inside viewportView.doLayout
, I am calling viewportView.setPreferredSize
. That seems to be wrong though because the scroll bar of the JScrollPane
is always updated according to the last setPreferredSize
before doLayout
. So it seems that in case of a revalidate, the JScrollPane
is first updating the scroll bar accordingly to the preferred size and then it calls doLayout
.
Can I change that behavior? Or where should I call setPreferredSize
? Or where should I put the code which layouts the child components?
I figured out one way which works:
Calling both this.setPreferredSize
and this.setSize
inside viewportView.doLayout
.
I leave this question open because I don't really understand why that works (and it doesn't if I remove one of them) and would like to know.
Ok, that worked because it generated an endless loop, i.e. it always pushed some revalidation request into the event loop and of course that solves the problem. However, that is not really a solution.
I now have this:
// In viewportView of the JScrollPane:
@Override public void doLayout() {
// ... layout childs ...
// size.x/size.y being the size I want to have for the viewportView
if(size.x != getPreferredSize().width || size.y != getPreferredSize().height) {
setPreferredSize(new Dimension(size.x, size.y));
if(getParent() != null) getParent().validate();
}
}
This seems to work fine now.
Still wonderin开发者_StackOverflow中文版g if someone could clarify if this is the right way to go or if not, what it would be.
If you want JScrollPane
's content (e.g. a JPanel
) size set it to the content. If you want JScrollPane
's size set it for the JScrollPane
. No need to call viewPortView's methods.
精彩评论