[英]Is there a method to move the caret of JTextArea upward vertically?
To move the caret of a JTextArea downward vertically without pressing the DOWN key, is it possible to do that programmatically? 若要垂直向下移动JTextArea的插入符而不按下DOWN键,是否可以以编程方式执行此操作?
In fact I want to write it in a KeyListener, but if I write like this: 实际上我想在KeyListener中编写它,但如果我这样写:
if((e.getKeyCode() == KeyEvent.VK_I) && ((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0)) {
try {
new Robot().keyPress(KeyEvent.VK_UP);
} catch (AWTException e) {
e.printStackTrace();
}
}
the UP key will be combined with the mac command key, and it becomes a page up action. UP键将与mac命令键组合,成为一个向上翻页动作。 So how can I deal with it? 那我该怎么处理呢?
Thanks for reading my question. 感谢您阅读我的问题。
I think to solve your problem instead of using Robot
just need to suppress current event and generate new: 我认为解决你的问题而不是使用Robot
只需要压制当前事件并生成新的:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Main2 {
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 20; i++) {
stringBuilder.append("This is text line.").append(System.lineSeparator());
}
JTextArea textArea = new JTextArea();
textArea.setText(stringBuilder.toString());
textArea.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println(e);
if((e.getKeyCode() == KeyEvent.VK_I) && ((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0)) {
e.consume(); // suppress current event
// send new KeyEvent
textArea.dispatchEvent(new KeyEvent(textArea, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, KeyEvent.VK_DOWN, (char)KeyEvent.VK_DOWN));
textArea.dispatchEvent(new KeyEvent(textArea, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), 0, KeyEvent.VK_DOWN, (char)KeyEvent.VK_DOWN));
}
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println(e);
}
});
JFrame frame = new JFrame();
frame.setSize(640, 480);
frame.getContentPane().add(textArea, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
FYI: Look to STDOUT. 仅供参考:期待STDOUT。 I think for any case you should suppress VK_I event in keyRelease
handler too. 我认为无论如何你也应该在keyRelease
处理程序中抑制VK_I事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.