Java - 按行号更新 JTextArea 中的文本

Java - Updating text from JTextArea by line number

它基于我的

我想按行号更新文本,
例如

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

我想将数字 2 中的文本更改为

birth : Singapore, 1 April 1989

找到行号的正确 Element,获取该行中字符串的 startend 偏移量,并将这些偏移量内的文本区域文本替换为新文本:

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();
     }
}

可运行示例(改编自):

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);
        });
    }
}

这是另一种可用于替换行号 (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));
}

它将文本视为字符串,并根据换行符进行字符串操作。