Is there a way to catch un-displayable characters before they are written to a JTextArea?
I alter my keyTyped behaviour to default output the char to the JTextArea, however when I copy and paste, it produces an un-displayable character.
I need this to work across multiple operating systems so using case 22: doesn't work as this doesn't apply on Mac's. Does sun either have a case for catching paste's/copy's free from OS constraints, or does someone know a good work-开发者_如何学编程around?
You might want to investigate document filters.
Adding a document filter will allow you to modify (or even prevent) a string that is added to the JTextArea
's document. A custom document filter can be added if your text area is using some subclass of AbstractDocument
as the document implementation. Something like this:
AbstractDocument doc = (AbstractDocument)textArea.getDocument();
doc.setDocumentFilter( new DocumentFilter() {
public void insertString( FilterBypass fb, int offset, String string,
AttributeSet attr ) throws BadLocationException
{
// Test string here and modify if required, then call super.insertString()
// (usually called on a "paste")
}
public void replace( FilterBypass fb, int offset, int length,
String text, AttributeSet attrs ) throws BadLocationException
{
// Test string here and modify if required, then call super.replace()
// (usually called when characters are typed)
}
});
(In your "real" implementation, you may want to test nicely that an AbstractDocument
is actually in use rather than the cast I've done).
I think you might be able to modify the clipboard behavior by:
- Create a TransferHandler that implements the importData() function
- Set the transferHandler on your function by calling JComponent.setTransferHandler()
精彩评论