如何设置包含 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);
目标是根据视口(viewport)的内容设置宽度,这样就不需要水平滚动条了。
应该是:
编辑:按照 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);
}
对我来说似乎有点老套,但它确实有效。
最佳答案
As you can see, I'm trying to figure out what to put on this line:
不要放任何东西。您不应该试图管理框架的大小。例如,您的代码甚至不考虑框架的边框。如果有的话,您的代码将更改为使用框架的宽度,而不是滚动 Pane 。
更好的方案是重写滚动面板的getPreferredSize()
方法返回super.getPreferredSize()
的宽度,然后指定一个合理的高度。您需要确保垂直滚动条始终可见才能使计算正常进行。
然后 pack() 方法将按预期工作。
关于java - 设置包含 JScrollPane 的容器的大小,以便滚动条不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22948003/