Java: Creating a Scrolling Text Area
This tip covers the basic technique for creating a standard text area that has the following features
- The ability to specify a height and width for the text area
- A vertical scroll bar that is always visible
- Word wrap within the text area
The complete code for this example is linked from the bottom of this page. The lines of code below show the basic steps for creating the text area.
The key lines are described as follows:
- Line 7 declares the text area
- Line 17 creates a new text area with no default text, a height of 5 lines and a width of 50 characters.
- Line 18 turns on word wrap for the text area. This prevents the text area from scrolling left and right.
- Line 19 adds text area to text area to a scroll pane, thus enabling scrolling.
- Line 20 is key. Without this statement, the scroll bar will not appear until there is enough text to require scrolling. Very ugly! By specifying JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, the scroll bar will always be visible irrespective of the text contained in the text area.
ta_scroll.java (Click to get source)
1:import javax.swing.*; 2:import java.awt.*; 3:import java.awt.event.*; 4: 5:public class ta_scroll{ 6: private JFrame f; //Main frame 7: private JTextArea ta; // Text area 8: private JScrollPane sbrText; // Scroll pane for text area 9: private JButton btnQuit; // Quit Program 10: 11: public ta_scroll(){ //Constructor 12: // Create Frame 13: f = new JFrame("Swing Demo"); 14: f.getContentPane().setLayout(new FlowLayout()); 15: 16: // Create Scrolling Text Area in Swing 17: ta = new JTextArea("", 5, 50); 18: ta.setLineWrap(true); 19: sbrText = new JScrollPane(ta); 20: sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 21: 22: // Create Quit Button 23: btnQuit = new JButton("Quit"); 24: btnQuit.addActionListener( 25: new ActionListener(){ 26: public void actionPerformed(ActionEvent e){ 27: System.exit(0); 28: } 29: } 30: ); 31: 32: } 33: 34: public void launchFrame(){ // Create Layout 35: // Add text area and button to frame 36: f.getContentPane().add(sbrText); 37: f.getContentPane().add(btnQuit); 38: 39: // Close when the close button is clicked 40: f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 41: 42: //Display Frame 43: f.pack(); // Adjusts frame to size of components 44: f.setVisible(true); 45: } 46: 47: public static void main(String args[]){ 48: ta_scroll gui = new ta_scroll(); 49: gui.launchFrame(); 50: } 51:}