【问题标题】:Adding JScrollPane to JPanel with another panels inside将 JScrollPane 添加到 JPanel,其中包含另一个面板
【发布时间】:2021-03-15 20:35:30
【问题描述】:

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

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

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);
        }       
    }   
}

}

【问题讨论】:

    标签: java swing jpanel jscrollpane


    【解决方案1】:
    1. 如果您想使用 JScrollPane,那么您的代码实际上需要使用 JScrollPane。您发布的代码甚至没有创建 JScrollPane。
    1. 如果您希望面板垂直显示,请不要使用 FlowLayout。 FlowLayout 是一种水平布局。您可以使用 BoxLayout 或 GridBagLayout。
    1. 为什么要创建“panel”变量并将其添加到内容窗格中?框架的内容窗格已经是使用 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);
    

    查看不同的结果。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多