java - 在 JTextArea 上调度关键事件不会移动插入符

标签 java swing simulation jtextarea

我想模拟 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/

相关文章:

java - 在查询中使用 NULL 作为占位符值时避免 IllegalArgumentException?

java - ChannelInboundHandlerAdapter和ChannelOutboundHandlerAdapter是否影响netty4中编码器和解码器的运行顺序?

java.lang.NoClassDefFoundError : org/apache/http/client/config/RequestConfig 错误

java - JFrame 无法正确显示

matlab - 如果已经执行了 MIL(循环中的模型)仿真,为什么在 HIL(循环中的硬件)之前使用 SIL(循环中的软件)?

python - 为什么我的 python 3 实现比我用 C++ 编写的快得多?

java - 想知道 Java object-json 序列化

java - JFileChooser:保存取消之前用户导航到的最后一个目录

java - 在 java 中绘制图形 - NetBeans IDE

simulation - 模拟一个网站