首页 > 解决方案 > 将 JScrollPane 添加到 JPanel,其中包含另一个面板

问题描述

我最近一直在做一些更大的项目,但不知道为什么 JScrollPane 不起作用。我以前从未使用过它,我在 stackOverflow 和其他编程论坛上阅读了许多关于它的已解决问题,但没有代码看起来与我的相似,以帮助我实现我的方法。这是我制作的新项目,旨在使其简短并展示一些示例。

在此处输入图像描述

红色是主面板,其中将包含另一个面板/JScrollPane,里面将是黑色的,我想让这个黑色的 Jpanel 可滚动并保存可能从 0 到 100+ 的任意数量的白色 JPanel

public class ScrollablePane {

private JFrame frame;
private JPanel panelCopy;
private JPanel panel;
private JPanel container;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ScrollablePane window = new ScrollablePane();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public ScrollablePane() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
        
    panel = new JPanel();
    panel.setBackground(Color.RED);
    panel.setBounds(0, 0, 434, 261);
    frame.getContentPane().add(panel);
    panel.setLayout(null);
    
    container = new JPanel();
    container.setBackground(Color.BLACK);
    container.setBounds(10, 10, 414, 241);
    container.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
    panel.add(container);
    
    for(int i = 0; i < 20; i++) {
        if(i > 0) {
            panelCopy = new JPanel();
            panelCopy.setPreferredSize(new Dimension(400, 40));     
            container.add(panelCopy);
        }       
    }   
}

}

标签: javaswingjpaneljscrollpane

解决方案


  1. 如果您想使用 JScrollPane,那么您的代码实际上需要使用 JScrollPane。您发布的代码甚至没有创建 JScrollPane。
  1. 如果您希望面板垂直显示,则不要使用 FlowLayout。FlowLayout 是一种水平布局。您可以使用 BoxLayout 或 GridBagLayout。
  1. 为什么要创建“面板”变量并将其添加到内容窗格?框架的内容窗格已经是使用 BorderLayout 的 JPanel。无需添加另一个面板

  2. 不要使用空布局!!!Swing 旨在与布局管理器一起使用。如果添加到滚动窗格的面板使用空布局,则滚动将不起作用。

因此,在您的情况下,基本逻辑可能类似于:

Box container = Box.createVerticalBox();
// add you child panels to the container. 

JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(container, BorderLayout.PAGE_START);

JScrollPane scrollPane = new JScrollPane(wrapper);

frame.add(scrollPane, BorderLayout.CENTER);

请注意,当滚动窗格大于“容器”面板的首选尺寸时,“包装”面板用于防止面板尺寸扩大。

尝试:

//JScrollPane scrollPane = new JScrollPane(wrapper);
JScrollPane scrollPane = new JScrollPane(container);

看到不同的结果。


推荐阅读