newbie
newbie

Reputation: 959

Java - Updating text from JTextArea by line number

It's based from my previous question.

I want update text by line number,
for E.g

name : andy
birth : jakarta, 1 jan 1990
number id : 01011990 01
age : 26
study : Informatics engineering

I want to change text in number 2 into

birth : Singapore, 1 April 1989

Upvotes: 2

Views: 1608

Answers (2)

Genti Saliu
Genti Saliu

Reputation: 2723

Find the proper Element for the line number, get the start and end offset of the string in that line and replace the textarea text within those offsets with the new text:

import javax.swing.JTextArea;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.BadLocationException;

public static void setTextInLineNo(JTextArea textArea, int lineNo, String newText) {
     Document doc = textArea.getDocument();
     Element root = doc.getDefaultRootElement();
     Element contentEl = root.getElement(lineNo - 1);

     int start = contentEl.getStartOffset();
     int end = contentEl.getEndOffset();

     try {
         // remove words in the line (-1 to prevent removing newline character)
         doc.remove(start, end - start - 1);
         doc.insertString(start, newText, null);
     } catch (BadLocationException e) {
         e.printStackTrace();
     }
}

Runnable example (adapted from answer to your previous question):

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;

public class TextAreaWithLine {

    private void setTextInLineNo(JTextArea textArea, int lineNo, String newText) {
        Document doc = textArea.getDocument();
        Element root = doc.getDefaultRootElement();
        Element contentEl = root.getElement(lineNo - 1);

        int start = contentEl.getStartOffset();
        int end = contentEl.getEndOffset();

        try {
            // remove words in the line (-1 to prevent removing newline character)
            doc.remove(start, end - start - 1);
            doc.insertString(start, newText, null);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }

    public JComponent makeUI() {
        String str = "name : andy\n"
                + "birth : jakarta, 1 jan 1990\n"
                + "number id : 01011990 01\n"
                + "age : 26\n"
                + "study : Informatics engineering\n";

        JTextArea textArea = new JTextArea(str);
        textArea.setEditable(false);
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(textArea));
        p.add(new JButton(new AbstractAction("change line") {
            @Override
            public void actionPerformed(ActionEvent e) {
                String lineNoStr = (String)JOptionPane.showInputDialog(
                        textArea.getRootPane(),
                        "Which line # to modify?",
                        "Line #:",
                        JOptionPane.PLAIN_MESSAGE,
                        null,
                        null,
                        "2");
                String value = (String)JOptionPane.showInputDialog(
                        textArea.getRootPane(),
                        "What value do you want to set it to?",
                        "Value:",
                        JOptionPane.PLAIN_MESSAGE,
                        null,
                        null,
                        "value");

                setTextInLineNo(textArea, Integer.parseInt(lineNoStr), value);
            }
        }), BorderLayout.SOUTH);
        return p;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            f.getContentPane().add(new TextAreaWithLine().makeUI());
            f.setSize(320, 240);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}

Upvotes: 1

Clark Kent
Clark Kent

Reputation: 1176

Here's another method that can be used to replace a line number (Java 8):

private void setTextInLineNo2(JTextArea textArea, int lineNo, String newText)
{
    String [] lines = textArea.getText().split("\n");
    lines[lineNo-1] = newText;
    textArea.setText(String.join("\n", lines));
}

It treats the text as a String, and does String manipulation based on new line delimiters.

Upvotes: 1

Related Questions