简体   繁体   English

如何将JScrollPane添加到JPanel

[英]How does one add a JScrollPane to a JPanel

I have been searching around for an easy way to implement a JScrollPlane . 我一直在寻找实现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). 我正在尝试将其添加到JPanel ,它将包含动态数量的JPanel (它将填充其他内容)。

Here is my (failing miserably) attempt to make said JScrollPane : 这是我(失败的)尝试使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);

In this example , a series of nested panels are added to a panel having BoxLayout . 在此示例中 ,将一系列嵌套面板添加到具有BoxLayout的面板中。 That panel is used to create a JScrollPane which is then added to a JFrame . 该面板用于创建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

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. 您遇到的主要问题是默认布局管理器的布局设置为FlowLayout ,这意味着JScrollPane将要使用其首选大小进行布局,这可能不会填满整个面板。

Instead, use a BorderLayout 而是使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM