如何将JScrollPane添加到JPanel [英] How does one add a JScrollPane to a JPanel
问题描述
我一直在寻找实现JScrollPlane
的简单方法.我正在尝试将其添加到JPanel
,它将包含动态数量的JPanel
s(将填充其他内容).
I have been searching around for an easy way to implement a JScrollPlane
. I am trying to add it to a JPanel
, and it will contain a dynamic number of JPanel
s (which will be filled with other stuff).
这是我(失败的)尝试做出所说的JScrollPane
:
Here is my (failing miserably) attempt to make said JScrollPane
:
final JPanel info = new JPanel();
final JScrollPane infoS = new JScrollPane(info,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
info.setLayout(new GridLayout(0,1));
info.setLocation(10,78);
info.setSize(420,490);
infoS.setPreferredSize(new Dimension(600, 600));
gui.add(infoS);
推荐答案
您遇到的主要问题是默认布局管理器的布局设置为FlowLayout
,这意味着JScrollPane
将要使用它的首选尺寸进行布局,这样可能无法填满整个面板.
The primary problem you're having is the fact that the default layout manager's layout is set to FlowLayout
, which means that the JScrollPane
will want to use it's preferred size to be layout with, which may not fill the entire panel.
相反,请使用BorderLayout
final JPanel info = new JPanel(new BorderLayout()); // <-- Change me :D
final JScrollPane infoS = new JScrollPane(info,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// These are bad ideas, setLocation and setSize won't work, as the panel should be
// under the control of a layout manager
//info.setLocation(10,78);
//info.setSize(420,490);
//infoS.setPreferredSize(new Dimension(600, 600));
gui.add(infoS);
这篇关于如何将JScrollPane添加到JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!