Adv Java - [Swing: JScrollPane Class]

♠ Posted by Unknown in at 21:19

JScrollPane Class


A scroll panes is a component that presents a rectangular area in which a component may be viewed. Horizontal and/or vertical scroll bars may be provided if necessary. Scroll panes are implemented in Swing by the JScrollPane class, which extends JComponent.
Some of its constructors are show here:

     JScrollPane(Component comp)
     JScrollPane(int vsb, int hsb)
     JScrollPane(Component comp, int vsb, int hsb)

Here, comp is the component to be added to the scroll pane, vsb and hsb are int constants that define when vertical and horizontal scroll bars for this scroll pane are shown. These constants are defined by the ScrollPaneConstants interface. Some example of these constants are described as follows:

Constants                                                Description

HORIZONTAL_SCROLLBAR_ALWAYS                           Always provide horizontal scroll bar.

HORIZONTAL_SCROLLBAR_AS_NEEDED                      Provide horizontal scroll bar, if needed.

VERTICAL_SCROLLBAR_ALWAYS                               Always provide vertical scroll bar.

VERTICAL_SCROLLBAR_AS_NEEDED                           Provide vertical scroll bar, if needed.

Here are the steps that you should follow to use a scroll pane in as applet:


  1. Create a JComponent object.
  2. Create a JScrollPane object. ( The argument to the constructor specify the component and the policies for vertical and horizontal scroll bars.)
  3. Add the scroll pane to the content pane of the applet.
Example:

/* <APPLET CODE = "JScrollExample.CLASS" WIDTH = 500 HEIGHT = 500></APPLET>
 */
 import java.awt.*;
 import javax.swing.*;
public class JScrollExample extends JApplet
{
          public void init()
          {
                   Container contentPane = getContentPane();
                   contentPane.setLayout(new BorderLayout());
                  
                   JPanel jp = new JPanel();
                   jp.setLayout(new GridLayout(20,20));
                   int b = 0;
                   for(int i = 0; i < 20; i++)
                   {
                             for(int j = 0; j< 20; j++)
                             {
                                      jp.add(new JButton("Vakratund : " + b));
                                      b++;
                             }
                   }
                  
                   int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
                   int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
                   JScrollPane jsp = new JScrollPane(jp, v, h);
                  
                   contentPane.add(jsp, BorderLayout.CENTER);
          }
Image: Swing JScrollPane Example 
}


0 comments:

Post a Comment