Java Swing:如何制作内部可能有按钮的项目的可滚动视图?

Java Swing: how to make scrollable view of items that may have buttons inside of them?

我正在尝试制作可滚动的项目列表,其中可能有按钮。它包含在 JTabbedPane 中,在彻底谷歌搜索后我仍然不确定如何继续。

我正在努力实现的目标的图片: 想到的最好的事情是 JScrollPane,它的项目是 JPanels 和 BoxLayout,它们有 "name of item | button | button",尽管我可能完全错了,JScrollPane 无法接受多个组件。

我需要帮助的是将这些 JPanel 添加到 JScrollPane。怎么做?我尝试了简单的 "this.add(name of panel)" 但它不起作用。

    // MainWindow:
    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("Overview", new OverviewTab());
    tabbedPane.addTab("Warehouse", new WarehouseTab());
    tabbedPane.addTab("History", new HistoryTab());

    public class WarehouseTab extends JScrollPane {
    WarehouseTab(){
        this.setBorder(null);
        this.add(new WarehouseItem());
        this.add(new WarehouseItem());
        this.add(new WarehouseItem());
        this.setVisible(true);
    }

    public class WarehouseItem extends JPanel {
    WarehouseItem(){
        this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
        JButton sell = new JButton("Sell");
        JButton tax = new JButton("Return tax");
        JLabel name = new JLabel("Item name");
        this.add(name);
        this.add(tax); 
        this.add(sell);
    }

我还尝试将我的 JPanel 打包到 Container 中,然后将 JScrollPane 的视口指向它,正如其他一些论坛上所建议的那样,但它也没有用。它还应该尝试什么?

如有任何建议,我们将不胜感激。

although I might be plain wrong and JScrollPane is unable to accept multiple Components.

是的,你是对的,JScrollPane 管理一个 "view"。您应该从一个单独的 JPanel 开始,它充当其他元素的 "primary" 容器,然后将其包装在 JScrollPane

public class WarehouseTab extends JPanel {
    public WarehouseTab() {
        setLayout(new BorderLayout());
        add(new JScrollPane(new WarehousePane());
    }
}

public class WarehousePane extends JPanel {
    WarehousePane(){
        setLayout(...); // Set an appropriate layout for overall needs
        this.add(new WarehouseItem());
        this.add(new WarehouseItem());
        this.add(new WarehouseItem());
    }

此外,请查看 How to Use Scroll Panes and the JavaDocs,其中提供了有关 JScrollPane 如何工作的更多信息