macaugmxus
macaugmxus

Reputation: 61

How to have scrolling in Java GUI JTextArea with Eclipse?

I am trying to put an muti lines text in the JtextArea, but there isn't a scrolling so I cannot move to see any data below the default JtextArea area, here is the code and textArea_1 is the JtextArea:

String abc="";
for(int i=0; i<=100; i++){
abc = abc + data[i][0]+"\n";
}
textArea_1.setText(abc);

Upvotes: 1

Views: 2823

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347194

Scrolling is handled by JScrollPane.

Check out How to use scroll panes and for your own reference, JScrollPane and which is also demonstrated in How to use Text Areas

Updated with example

enter image description here

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestScrollPane04 {

    public static void main(String[] args) {
        new TestScrollPane04();
    }

    public TestScrollPane04() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JTextArea textArea = new JTextArea(10, 20);
                String abc = "";
                for (int i = 0; i <= 100; i++) {
                    abc = abc + "This is some additional text " + i + "\n";
                }
                textArea.setText(abc);

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(textArea));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

Upvotes: 1

Shahrzad
Shahrzad

Reputation: 1072

You should add a JScrollPane. as

JscrollPane myScroll=new JScrollPane(textArea_1);

If your text is more than that can see other text by scrolling. By default when you set or append text to JTextArea it scrolls to end (you can see that if text is large so that scroll bar appeard). So to scroll back to first line try

textArea_1.setCaretPosition(0);

see Java doc

Upvotes: 0

Tdorno
Tdorno

Reputation: 1571

You need to look into adding a JScrollPane.

Link: http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html

import javax.swing.JScrollPane;
JScrollPane scrollPane = new JScrollPane(TEXTAREAHERE);

Upvotes: 2

Related Questions