我正在编写一个文本编辑器(用java),其中我使用JTextArea进行主要文本编辑,并将文本放入字符串生成器中。
当我突出显示文本并执行删除该文本 block 之类的操作时,我希望它在字符串生成器中更新。
所以我的问题是,有没有办法获取字符串生成器中突出显示文本的第一个和最后一个索引?
谢谢。
最佳答案
您可以使用 DocumentListener
使它们保持同步,如下所示。然而,我强烈建议您重新考虑您在这里尝试采取的任何方法。看起来您正在尝试使用外部 StringBuilder 作为 JTextArea 的“模型”,但文档就是模型。所以我不知道什么时候这会是一个好主意。
public static void main(String[] args) {
JTextArea area = new JTextArea();
final StringBuilder builder = new StringBuilder();
area.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
builder.delete(e.getOffset(), e.getOffset() + e.getLength());
System.out.println("Removed " + e.getLength() + " chars from SB");
}
@Override
public void insertUpdate(DocumentEvent e) {
try {
builder.insert(e.getOffset(),
e.getDocument().getText(e.getOffset(), e.getLength()));
System.out.println("Inserted " + e.getLength() + " chars into SB.");
} catch ( BadLocationException ble ) {
ble.printStackTrace();
}
}
@Override public void changedUpdate(DocumentEvent e) { /* no-op */ }
});
final JFrame frame = new JFrame("DocumentListener Test");
frame.add(area);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("Final SB contents:");
System.out.println(builder.toString());
}
});
frame.pack(); frame.setVisible(true);
}
关于java - 获取 JTextArea 中突出显示文本的第一个和最后一个索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3188505/