Getting the first and last index values of highlighted text in a JTextArea
I am writing a text editor(in java) where I am using a JTextArea for the main text editing and I am putting the text into a stringbuilder.
When I highlight the text and do something like delet开发者_开发知识库e that block of text, I want it to update in the stringbuilder.
So my question is, is there a way to get the first and last index of the highlighted text in the stringbuilder?
Thanks.
You can keep them in sync using a DocumentListener
as below. However, I heavily recommend rethinking whatever approach you're trying to take here. It seems like you're trying to use an external StringBuilder as the "model" to your JTextArea, but the Document is the model. So I fail to see when this would be a good idea.
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);
}
If you delete the text in JTextArea, can't you just call getText();
on your JTextArea to get the updated text?
I'm assuming that (in your stringbuilder) you're keeping a record of the string that was not deleted. If you want to keep a record of the stuff that gets deleted, you can compare what was in the JTextArea originally to the updated one to find out what was deleted. You can do this by finding out at which index the original and the updated versions differ and where they match afterwards.
精彩评论