如何设置包含JScrollPane
的容器的大小,使滚动条不会出现?
考虑一下这个SSCCE (使用MigLayout):
public static void main(String[] args) {
JPanel panel = new JPanel(new MigLayout());
for(int i = 0; i < 15; i++) {
JTextArea textArea = new JTextArea();
textArea.setColumns(20);
textArea.setRows(5);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane jsp = new JScrollPane(textArea);
panel.add(new JLabel("Notes" + i));
panel.add(jsp, "span, grow");
}
JScrollPane jsp = new JScrollPane(panel);
JFrame frame = new JFrame();
frame.add(jsp);
frame.pack();
frame.setSize(jsp.getViewport().getViewSize().width, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
正如你所看到的,我正在试图找出在这条线上写些什么:
frame.setSize(jsp.getViewport().getViewSize().width, 500);
目标是设置相对于视口内容的宽度,这样就不需要水平滚动条了。
应:
编辑:按照camikr的建议,这就是结果:
public static final int pref_height = 500;
public static void main(String[] args) {
JPanel panel = new JPanel(new MigLayout());
for(int i = 0; i < 15; i++) {
JTextArea textArea = new JTextArea();
textArea.setColumns(20);
textArea.setRows(5);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane jsp = new JScrollPane(textArea);
panel.add(new JLabel("Notes" + i));
panel.add(jsp, "span, grow");
}
JScrollPane jsp = new JScrollPane(panel) {
@Override
public Dimension getPreferredSize() {
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Dimension dim = new Dimension(super.getPreferredSize().width + getVerticalScrollBar().getSize().width, pref_height);
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
return dim;
}
};
JFrame frame = new JFrame();
frame.add(jsp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
对我来说有点刻薄,但很管用。
发布于 2014-04-08 21:03:24
正如你所看到的,我正在试图找出在这条线上写些什么:
什么都别放。您不应该试图管理框架的大小。例如,您的代码甚至不考虑框架的边界。如果有任何更改,代码将更改为使用框架的宽度,而不是滚动窗格。
更好的解决方案是重写滚动窗格的getPreferredSize()
方法以返回super.getPreferredSize()
的宽度,然后指定合理的高度。您需要确保垂直滚动条总是可见的,这样计算才能工作。
那么pack()方法将按预期工作。
发布于 2018-05-08 09:32:02
水平情况也是一样的:
new JScrollPane(panel) {
public Dimension getPreferredSize() {
Component view = getViewport().getView();
if (view == null) return super.getPreferredSize();
int pref_width = view.getPreferredSize().width;
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
Dimension dim = new Dimension(pref_width, super.getPreferredSize().height + getHorizontalScrollBar().getSize().height);
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
return dim;
}
}
此外,如果您稍后切换出滚动窗格中的视图,它也会适当地进行调整。
https://stackoverflow.com/questions/22948003
复制相似问题