【问题标题】:java - inserting text using JTextArea by number linejava - 通过数字行使用 JTextArea 插入文本
【发布时间】:2016-01-12 07:43:14
【问题描述】:

就我而言,我想通过数字行在 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

【问题讨论】:

  • 当您使用jTextArea.getDocument.insertString 方法时,您遇到了一些错误,或者您的文本没有被插入?
  • 那么,我该怎么办?
  • 您需要计算文档中代表第 3 行的位置,this 可能会给您一些想法
  • 你能举一些例子吗???

标签: java swing jtextarea line-numbers


【解决方案1】:

您可以使用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);
    });
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    相关资源
    最近更新 更多