Java - 按行号从JTextArea更新文本

时间:2016-01-18 14:46:21

标签: java jtextarea

它来自我的previous question

我希望按行号更新文字,
对于E.g

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

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

birth : Singapore, 1 April 1989

2 个答案:

答案 0 :(得分:1)

为行号找到正确的Element,获取该行中字符串的startend偏移量,并用新文本替换这些偏移量中的textarea文本: / p>

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示例(改编自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);
        });
    }
}

答案 1 :(得分:1)

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

它将文本视为String,并根据新的行分隔符进行字符串操作。