I faced this new thing today, and I didn't know why. When I want to show something in panel for example, I just add it to panel; but why I cannot add a table to scroll pane directly, and why I have to call the setviewportview()
method? What does add()
method do and what does setViewProtView()
do?
Asked
Active
Viewed 1.1k times
4
1 Answers
20
Basically, you should not use JScrollPane#add
.
JScrollPane
has a single component already attached to it, a JViewport
, this is what the JScrollPane
uses to display any component added to the view port.
setViewportView
is a convenience method for for JScrollPane#getViewport#setView
The basic concept comes down to the fact that from the scroll panes point of view, it will only show a single component, so add
doesn't actually make any sense for it. The method is a consequence of extending from JComponent
-> Container

MadProgrammer
- 343,457
- 22
- 230
- 366
-
1Great answer. I found several answers pointing to use setViewPortView, but no one explained like you did here - 1. basically JScrollpane already has a component called Viewport, 2. add is just redundant method came through inheritance! Thanks for explaining it nicely. – svaratech Mar 06 '15 at 18:54
-
Why couldn't JScrollPane#add be overridden to behave as expected? – gdbj Apr 13 '17 at 19:14
-
1@gdbj You'd have to ask the original framework developers, but, `add` comes from `java.awt.Container`, so it's inheritance issue – MadProgrammer Apr 13 '17 at 22:28