java - Dispatching key events on JTextArea doesn't move the caret -


i want simulate key presses on jtextarea. use robot class, window want type in doesn't have focus. have scenario this:

public class test {   public static void main(string[] args) {     frame frame = new frame();     jtextarea text = new jtextarea();     frame.add(text);     frame.pack();     frame.setvisible(true);      text.dispatchevent(new keyevent(text,           keyevent.key_typed, 0,           0,           keyevent.vk_undefined, 'h'));     text.dispatchevent(new keyevent(text,           keyevent.key_typed, 0,           0,           keyevent.vk_undefined, 'l'));   } } 

but after h typed, caret not moved right, causes l typed before h: final text in area lh, want hl.

i can dispatch new key event in between h , l move caret right (the right arrow) or call setcaretposition , work, searching solution doesn't move caret manually , behaves person typing (i making tester testing assignments students).

any ideas?

customise caret update position.

final defaultcaret caret = new defaultcaret(); caret.setupdatepolicy(defaultcaret.always_update); text.setcaret(caret); 

from defaultcaret javadoc

the following update policies allowed:

never_update: caret stays @ same absolute position in document regardless of document updates, except when document length becomes less current caret position due removal. in case caret position adjusted end of document. caret doesn't try keep visible scrolling associated view when using policy.

always_update: caret tracks document changes. regular changes increases position if insertion occurs before or @ current position, , decreases position if removal occurs before current position. undo/redo updates moved position update occurred. caret tries keep visible calling adjustvisibility method.

update_when_on_edt: acts always_update if document updates performed on event dispatching thread , never_update if updates performed on other thread.

the default property value update_when_on_edt.


Comments