java - 在 Java 中向 JPanel 添加滚动条

标签 java swing scrollbar panel

所以我已经尝试了一段时间,但似乎无法使其发挥作用。

好的,我正在 netbeans 中制作一个目录并使用 Java。我从调色板窗口拖入一个 JPanel 并将其命名为“panel”。唯一的问题是我无法使面板垂直滚动。

我在这里阅读了一些问题并在网上搜索,发现我可以在 Java 中使用 JScrollPane ,唯一的问题是每当我尝试使用它时,面板似乎消失了,当我不添加它时,它工作正常,问题是我的所有其他元素都从面板溢出。

这是我正在使用的代码:

initComponents();

//Just adding some elements in the panel
for(int i = 1; i <= 10; i++){
        //Position elements in a new line so they won't overflow to the right
        if(counter == 7){
            locationTop += 350;
            locationLeft = 90;
            locationTopViewMore += 350;
            locationTopAgregar += 550;
            counter = 0;
        }

        //Adding an image and a couple of buttons
        JLabel myLabel= new JLabel();
        myLabel.setIcon(new ImageIcon("" + save)); //Adding an image
        myLabel.setSize(200, 200);
        myLabel.setLocation(locationLeft, locationTop);
        panel.add(myLabel);

        JButton btnViewMore = new JButton("View More"); //Making a button.
        btnViewMore.setSize(100, 50);
        btnViewMore.setLocation(locationLeft + 50, locationTopViewMore);
        panel.add(btnViewMore);

        JButton btnAgregar = new JButton("Another Button"); //Making another button.
        btnAgregar.setSize(150, 50);
        btnAgregar.setLocation(locationLeft + 25, locationTopAgregar);
        panel.add(btnAdd);

        locationLeft += 200;
        counter++;
}
//JScrollPane scrollPane = new JScrollPane(panel);

这就是我不使用 JScrollPane 时发生的情况:

http://i57.tinypic.com/acel3s.png

这就是我使用 JScrollPane 时发生的情况:

http://i57.tinypic.com/2ltlcwj.png

非常感谢任何帮助。谢谢!

最佳答案

我无法通过查看该片段来判断,但是您是否将滚动 Pane 添加到了框架中?这似乎太明显了,不容忽视,但以防万一。此外,您只能向一个父级添加一个 swing 小部件,这解释了为什么添加面板的代码也不起作用,但是当您取消注释scrollPane 时,一切都会起作用。

关于java - 在 Java 中向 JPanel 添加滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30089813/

相关文章:

java - 无法安装通用编解码器 jar 文件

java - 过滤时很漂亮的 JSON 导入,但返回整批数据时则不然 + ID 中丑陋的括号

java - 刷新文本/JLabel 值

java - Graphics2D DrawImage不代表图像大小

java - 如何创建水平 slider

java - 安卓编程: TextView isn't displaying full string

java - 从另一个类更改 Java 卡布局中的 Activity "card"

python - 如何在 Tkinter 列表框中插入时添加自动滚动?

c#:如何确定当前是否显示了 Scrollable 控件的 ScrollBar?

html - 为什么 1px 的边框会抵消 100px 的 margin-top 并杀死滚动条?