java - 使用JTextArea按数字行插入文本

时间:2016-01-12 07:43:14

标签: java swing jtextarea line-numbers

对于我的情况,我想通过数字行在JTextArea中插入文本。

例如

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

所以,我想在第3行的最后位置插入文字。

我想我可以用: jTextArea.getDocument.insertString(3," my text here".null);
但它没有用。

所以,我希望我的输出是这样的。

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

1 个答案:

答案 0 :(得分:4)

您可以使用Element#getElement(int)方法:

import java.awt.*;
import java.awt.event.*;
import java.util.Optional;
import javax.swing.*;
import javax.swing.text.*;

public class ElementEndOffsetTest {
  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("add") {
      @Override public void actionPerformed(ActionEvent e) {
        Document doc = textArea.getDocument();
        Element root = doc.getDefaultRootElement();
        Optional.ofNullable(root.getElement(2)).ifPresent(el -> {
          try {
            doc.insertString(el.getEndOffset() - 1, " my text here", null);
          } catch (BadLocationException ex) {
            ex.printStackTrace();
          }
        });
      }
    }), 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 ElementEndOffsetTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}