Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert or append new line on top of the jtextarea in java swing?

how to insert or append new line on top of the jtextarea in java swing ? i want to to append jtextarea and add the new line on top of the jtextarea please help me how to do this.

like image 416
sandybarasker Avatar asked Sep 24 '12 12:09

sandybarasker


3 Answers

You can do this:

textArea.setText("The new text\n" + textArea.getText());

Or, an even better solution would be this:

try {
  textArea.getDocument().insertString(0, "The new text\n", null);
} catch (BadLocationException e) {
  e.printStackTrace();
}
like image 65
Dan D. Avatar answered Oct 21 '22 11:10

Dan D.


Your best option is to directly modify the underlying Document of the JTextArea.

Here is a small demonstration of this:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;

public class TestTextArea {

    private void initUI() {
        JFrame frame = new JFrame("test");
        final JTextArea textarea = new JTextArea(24, 80);
        JButton addText = new JButton("Add line");
        addText.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    textarea.getDocument().insertString(0, "New line entered on " + new Date() + "\n", null);
                } catch (BadLocationException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(textarea));
        frame.add(addText, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

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

            @Override
            public void run() {
                new TestTextArea().initUI();
            }
        });
    }

}
like image 40
Guillaume Polet Avatar answered Oct 21 '22 12:10

Guillaume Polet


textArea.setText("this is new line" + "\n" + textArea.getText())

like image 1
AlexR Avatar answered Oct 21 '22 10:10

AlexR