Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrollbars on JTextArea in a JScrollPane do not work

I'm having trouble getting a JTextArea to scroll. I'm not sure how you can mess up a JScrollPane but I seem to have and I just can't see it. It's all part of a larger project but the code below is how I'm creating a JTextArea and adding it to a JScrollPane. When you type beyond the edge of the text area the scrollbar doesn't appear. Setting the vertical scrollbar to always on gives a scrollbar that doesn't do anything.

import javax.swing.*;
import java.awt.*;

public class TextAreaTest extends JFrame{

    public TextAreaTest() {
     super("Text Area Scroller");

     Container c = getContentPane();

     JTextArea textarea = new JTextArea();
     textarea.setPreferredSize(new Dimension(300, 50));
     textarea.setLineWrap(true);
     textarea.setText("xx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\n");

     JScrollPane scroller = new JScrollPane(textarea);

     c.add(scroller, BorderLayout.CENTER);
     pack();
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String args[]){
     TextAreaTest instance = new TextAreaTest();
     instance.setVisible(true);
    }
}

I've tried setting the text area text, or rows and columns, in the constructor, neither of which worked. It's doing my head in. Any ideas?

like image 540
Robert Avatar asked Apr 21 '10 22:04

Robert


People also ask

What happens if you press Enter in a JTextArea?

If focus is on a JTextField and enter is pressed, the text field fires an ActionEvent.

Can you type in a JTextArea?

The JTextArea class provides a component that displays multiple lines of text and optionally allows the user to edit the text. If you need to obtain only one line of input from the user, you should use a text field.

How do I make JScrollPane transparent?

You need to use setOpaque(false) to make it transparent. Call that both on the JScrollPane, and on it's ViewPort. sp. setOpaque(false); sp.


2 Answers

Set the preferred size of the scroll pane rather than the text area.

like image 101
ColinD Avatar answered Oct 18 '22 02:10

ColinD


The others are right about the size. As an aside, consider starting on the Event Dispatch Thread (EDT):

public static void main(String args[]) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            new TextAreaTest().setVisible(true);
        }
    });
}
like image 34
trashgod Avatar answered Oct 18 '22 01:10

trashgod