JScrollPane Example Java Swing

JScrollPane Example Java Swing

JScrollPane scrolls to view the contents of the component added to it. Scrollbars are used to scroll the contents horizontally and vertically. From JDK 1.4, new methods for mouse wheel movements are added like processMouseWheelEvent(MouseWheelEvent) etc. The mouse wheel can be used to enlarge a photo by rotating the wheel in the display area.

Following example uses JScrollPane.


JScrollPane
Output screen of JScrollPane Example

In the above program, 400 buttons (20 rows x 20 columns) can be viewed by adding to JScrollPane. If added to a frame or panel directly (without using scroll pane), all are not visible. They are added to a panel and the panel is added to a scroll pane. Using scrollbars, all the contents can be viewed. This is the advantage with scroll pane. In the earlier program, JList is added to scroll pane.

Programmer can be choosy about the appearance of scrollbars. Other options for ScrollPaneConstants are

ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER;
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;

The above options apply to horizontal scrollbar also. The first option gives scrollbars if needed only. Needed means if the display area is more and contents are less, scrollbars are not given and if the contents are more the scrollbars are given. Never means the scrollbars are not given even if needed. Always means whether needed are not, scrollbars are given always.

Leave a Reply

Your email address will not be published. Required fields are marked *