VextoR
VextoR

Reputation: 5165

How does JScrollPane understand when it needs to show scroll bars?

We have a component Component mainComp, which will be inside a scrollPane;

scrollPane.add(mainComp);

at some point something like this gets called

mainComp.setPreferredSize(null);
Component parent = jframe1.getParent();
while (parent != null){
  parent.setPreferredSize(null);
  parent = parent.getParent();
}

after this the scrolling bars gets disappeared and appear again only if I resize JFrame via mouse.

I don't understand how to make JScrollPane force to recalculate whether it needs to show the scrolling bars. Is it possible?

Upvotes: 1

Views: 655

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

at some point something like this gets called

mainComp.setPreferredSize(null);
Component parent = jframe1.getParent();
while (parent != null){
  parent.setPreferredSize(null);
  parent = parent.getParent();
}
after this the scrolling bars gets disappeared and appear again only if I resize JFrame via mouse.

So I can't understand how to make JScrollPane force to recalculate \ rethink that it needs to show the scrolling bars?

The JScrollPane looks at the size of the component held by its JViewPort and if larger than the size of the JViewPort, the scroll bars are displayed. When you make the preferred size of the component held by the JScrollPane null, then that messes with its size (in lord knows what way, I've never seen such code to be honest), and you loose your scroll bars. The solution in my mind is not to call setPreferredSize(null). Ever. There must be a better way to achieve what you're trying to do, and if you tell us more about your code and problem, we'll likely be able to help you find this. I have to wonder if your question may in fact be an XY Problem in disguise.

Upvotes: 2

durron597
durron597

Reputation: 32333

You can force the JScrollPane to always show the scrollbar using setHorizontalScrollBarPolicy and setVerticalScrollBarPolicy:

scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

See: Setting the Scroll Bar Policy

On startup, the scroll pane in the ScrollDemo application has two scroll bars. If you make the window large, both scroll bars disappear because they are no longer needed. If you then shrink the height of the window without changing its width, the vertical scroll bar reappears. Further experimentation will show that in this application both scroll bars disappear and reappear as needed. This behavior is controlled by the scroll pane's scroll bar policy, Actually, it's two policies: each scroll bar has its own.


Note: while this answers the question you've asked, please see @HovercraftFullOfEels answer about why you should never use setPreferredSize(null) EVER.

Upvotes: 2

Related Questions