When many components are placed inside a container, and the display area of the container is not sufficient to display all the components at the same time, if the container has a scrollbar, the components in the position of the container can be seen by moving the slider of the scroll bar. The scroll panel JScrollPane can achieve this requirement, JScrollPane is a panel with scroll bars. JScrollPane is a subclass of the container class and a container, but only one component can be added. The general use of JScrollPane is to add some components to a jpanel before adding the JPanel to JScrollPane. Thus, from the interface, it appears that there are multiple components on the scrolling panel. In Swing , components such as JTextArea, JList, jtable, etc. do not have their own scroll bars, they need to be placed on the scroll panel, using the scroll bar of the scrolling panel to navigate through the contents of the component.
The JScrollPane class is constructed in the following ways:
-
JScrollPane (), create the JScrollPane object first, and then use the method Setviewportview (Component com) to place the Component object for the scroll panel object.
-
JScrollPane (Component com), create JScrollPane object, parameter COM is the component object to be placed on the JScrollPane object. After you have specified a display object for the JScrollPane object, use the Add () method to place the JScrollPane object in the window.
The JScrollPane object sets the scroll bar in the following ways:
-
Sethorizontalscrollbarpolicy (int policy), policy takes one of the following 3 values:
Jscrollpane.horizontal_scrollbar_always
Jscrollpane.horizontal_scrollbar_as_need
Jscrollpane.horizontal_scrollbar_never
-
Setverticalscrollbarpolicy (int policy), policy takes one of the following 3 values:
Jscrollpane.vertical_scrollbar_always
Jscrollpane.vertical_scrollbar_as_need
Jscrollpane.vertical_scrollbar_never
The following code places the text area in the scrolling panel, and the scroll bar of the slide panel allows you to navigate the text area
JTextArea texta = new JTextArea (20,30);
JScrollPane jsp = new JScrollPane (texta);
Getcontentpane (). Add (JSP);//Add a scroll panel with text area to the current window
Java Swing Component JScrollPane