如何将JScrollPane添加到JPanel

时间:2012-11-19 20:04:47

标签: java swing jpanel jscrollpane

我一直在寻找一种简单的方法来实现JScrollPlane。我正在尝试将其添加到JPanel,并且它将包含动态数量的JPanel s(将填充其他内容)。

这是我(失败的)尝试说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);

2 个答案:

答案 0 :(得分:2)

在此example中,将一系列嵌套面板添加到具有BoxLayout的面板中。该面板用于创建JScrollPane,然后将其添加到JFrame

public class BoxTest extends JPanel {
...
JScrollPane jsp = new JScrollPane(this,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
...
JFrame f = new JFrame();
f.add(jsp); // BorderLayout.CENTER, by default

答案 1 :(得分:2)

您遇到的主要问题是默认布局管理器的布局设置为FlowLayout,这意味着JScrollPane会希望使用它的首选大小进行布局,可能无法填满整个小组。

相反,请使用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);
相关问题