我想模拟 JTextArea 上的按键。我会使用 Robot 类,但我想要输入的窗口没有焦点。所以我有这样的场景:
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'));
}
}
但是在输入 H 后,插入符号没有向右移动,这导致在 H 之前输入 L:该区域中的最终文本是 LH,但我希望它是 HL。
我可以在 H 和 L 之间调度一个新的按键事件,该事件会将插入符号向右移动(右箭头)或调用 setCaretPosition,这会起作用,但我正在寻找一种不会手动移动插入符号的解决方案,并且行为就像一个人打字(我正在制作一个测试器来测试学生的作业)。
有什么想法吗?
最佳答案
自定义插入符以始终更新其位置。
final DefaultCaret caret = new DefaultCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
text.setCaret(caret);
来自 DefaultCaret JavaDoc
The following update policies are allowed:
NEVER_UPDATE: the caret stays at the same absolute position in the document regardless of any document updates, except when document length becomes less than the current caret position due to removal. In that case caret position is adjusted to the end of the document. The caret doesn't try to keep itself visible by scrolling the associated view when using this policy.
ALWAYS_UPDATE: the caret always tracks document changes. For regular changes it increases its position if an insertion occurs before or at its current position, and decreases position if a removal occurs before its current position. For undo/redo updates it is always moved to the position where update occurred. The caret also tries to keep itself visible by calling adjustVisibility method.
UPDATE_WHEN_ON_EDT: acts like ALWAYS_UPDATE if the document updates are performed on the Event Dispatching Thread and like NEVER_UPDATE if updates are performed on other thread.
The default property value is UPDATE_WHEN_ON_EDT.
关于java - 在 JTextArea 上调度关键事件不会移动插入符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30119201/