Java Reference
In-Depth Information
Working with Scroll Panes
When using text areas with AWT, scroll bars are managed by the TextArea object. In Swing,
scroll bars in a JTextArea are managed by a separate object. You can use the JScrollPane
class to add scroll bars to a JTextArea using the constructor:
public JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
The Component parameter represents the component that needs scroll bars. The
vsbPolicy and hsbPolicy parameters represent the scroll bar policies for the JScrollPane. The
possible values are found in the javax.swing.ScrollPaneConstants interface. Examples
include HORIZONTAL_SCROLLBAR_ALWAYS and VERTICAL_SCROLLBAR_AS_NEEDED.
For example, the following ScrollPaneDemo program demonstrates adding scroll bars to
a JTextArea. Study the program and try to determine how the GUI looks.
import javax.swing.*;
import java.awt.*;
public class ScrollPaneDemo extends JFrame
{
JTextArea textArea;
public ScrollPaneDemo(String title)
{
super(title);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container contentPane = this.getContentPane();
textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
contentPane.add(pane, BorderLayout.CENTER);
}
public static void main(String [] args)
{
JFrame f = new ScrollPaneDemo(“ScrollPaneDemo”);
f.setSize(300,200);
f.setVisible(true);
}
}
Figure13.9 shows what happens when enough text is entered to display the horizontal
scroll bar, which does not appear initially.
continued
Search WWH ::




Custom Search