且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Java 中将 ScrollPane 添加到面板?

更新时间:2023-11-30 16:49:10

像这样创建面板和滚动面板:

JPanel panel = new JPanel();JScrollPane scrollPane = new JScrollPane( panel );

在运行时向面板添加按钮时,代码应为:

panel.add( button );panel.revalidate();

只要您使用布局管理器,就会重新计算首选大小并显示滚动条.

I want to add different buttons, vertically stacked, to a JPanel at run-time and use a JScrollPane so that all buttons will be visible (with some scrolling).

In order to do this, I have added my JPanel to a JScrollPane, after which I add buttons to my JPanel.

However, when I do this the vertical scrollbar does not allow me to see all images. For example when I add 7 buttons I can only scroll to see 5 full images and half of the 6 images.

Why doesn't my scrollbar allow me to display all 7 buttons?

Create the panel and scrollpane like:

JPanel panel = new JPanel();
JScrollPane scrollPane = new JScrollPane( panel );

When you add buttons to the panel at run time the code should be:

panel.add( button );
panel.revalidate();

As long as you are using a layout manager the preferred size will be recalculated and the scrollbar will appear.