A JScrollBar is a component and it doesn't handle its own events whereas a JScrollPane is a Container and it handles its own events and performs its own scrolling. A JScrollBar cannot have a JScrollPane whereas a JScrollPane can have a JScrollBar.
JScrollBar
- The object of the JScrollBar class is used to add horizontal and vertical scrollbar which allow the user to select items between a specified minimum and maximum values.
- A JScrollBar class is an implementation of a scrollbar and inherits the JComponent class.
Syntax
public class JScrollBar extends JComponent implements Adjustable, Accessible
Example
import javax.swing.*; import java.awt.*; public class JScrollBarTest extends JFrame{ JScrollBarTest() { setTitle("JScrollBar Test"); JScrollBar jsb = new JScrollBar(); setLayout(new FlowLayout()); add(jsb); setSize(350, 275); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String args[]) { new JScrollBarTest(); } }
Output
JScrollPane
- A JSrollPane is used to make a scrollable view of a component.
- A scroll pane is an object of the JScrollPane class which extends JComponent class.
- When screen size is limited, we use a scroll pane to display a large component or a component whose size can change dynamically.
- The important methods of JScrollPane class are setColumnHeaderView(), setRowHeaderView(), setViewportView() and etc.
Example
import javax.swing.*; import java.awt.*; public class JScrollPaneTest extends JFrame { JScrollPaneTest() { setTitle("JScrollPane Test"); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); JScrollPane jsp = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); add(jsp); setSize(350, 275); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JScrollPaneTest(); } }