我们有一个组件 Component mainComp
,它会在一个 scrollPane 里面;
scrollPane.add(mainComp);
在某些时候会调用这样的东西
mainComp.setPreferredSize(null);
Component parent = jframe1.getParent();
while (parent != null){
parent.setPreferredSize(null);
parent = parent.getParent();
}
此后滚动条消失,只有当我通过鼠标调整 JFrame
的大小时才会再次出现。
我不明白如何让 JScrollPane
强制重新计算是否需要显示滚动条。可能吗?
最佳答案
您可以使用 setHorizontalScrollBarPolicy
和 setVerticalScrollBarPolicy
强制 JScrollPane
始终显示滚动条:
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
参见: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.
注意:虽然这回答了您提出的问题,但请参阅 @HovercraftFullOfEels answer about why you should never use setPreferredSize(null)
EVER.
关于java - JScrollPane 如何理解何时需要显示滚动条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31924626/