Table of Contents
Working with ScrollPanes in Java
Scrollbars are an integral part of any interface. To show any content that extends beyond the length of a certain page, you most definitely will need a scroll pane or a scrollbar. Scrollbars also come into play when dynamically resizing a page. For example, when you contract the window size from full screen to any other size, a scrollbar immediately appears to the right and bottom of the page such that you can see all the content of that page.
How to Create a ScrollPane
As this component is part of the Java Swing Package, you will first and foremost need to import the package:
import javax.swing.*;
Once done, you can call a new ScrollPane object: JScrollPane sp = new JScrollPane();
Constructors
- JScrollPane() – This will just create a new ScrollPane object or component.
- JScrollPane(Component) – The Component sets the scroll pane’s client.
- JScrollPane(int, int) – The two int parameters assume the horizontal and vertical policies of the scroll pane.
- JScrollPane (Component, int, int) – This scrollpane will have a component as well as horizontal and vertical policies.
Useful Methods
- void setColumnHeaderView (Component) – This will set column header
- void setRowHeaderView (Component) – Sets the row header
- setCorner (String, Component) – This will set the specified corner as determined by the int parameter.
- getCorner(String) – A ScrollPane has several corners like UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER, LOWER_LEFT_CORNER, and so on. This method will get the corner.
Example
The following will demonstrate how to create a vertical and horizontal scroll pane on your application window.
import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JtextArea; public class JScrollDemo { private static void showBar() { final JFrame frame = new JFrame(“Scroll Pane Demo”); frame.setSize(500,500); frame.setVisible(true); frame.setDefaultCloseOPeration(JFrame.EXIT_ON_CLOSE); //We will be using a flow layout here //Assigning the flow layout to the frame frame.getContentPane).setLayout(new Flow Layout()); JTextArea = new JTextArea(20,20); JScrollPane scroll = new JScrollPane(text Area); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); frame.getContentPane().add(scroll); } public static void main (String args []) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run () { showBar(); } }); } }
OUTPUT
A blank window will be created with two scrollbars at the bottom and at the right of your screen just like you see on a webpage while surfing the Internet.
0 Comments