【发布时间】:2019-01-21 20:30:51
【问题描述】:
这段代码的主要目的是一种在 JFrame 中使用 keyListeners 的 AutoHotKey。 AutoHotKey 更容易使用,并且会提供更快的解决方案,但我写这篇文章是为了学习
我正在尝试让我的一个 keyListeners (KeyPressed) 从机器人 keyPress 而不是用户 keyPress 获取输入。我创建了一个 Robot 对象并发送了 keyPress 和 keyRelease 但程序仍然要求用户提供另一个输入。
我想要发生的事情是触发 keyPress 事件,并且 keyListener 将其作为用户的输入并继续执行程序的其余部分,最终将关闭它。
当前代码:
public class Main extends JFrame implements KeyListener {
private static final long serialVersionUID = 7225065896901900132L;
/**
* Aye, I do not recommend storing passwords as plain text if it is for
* something important but here is this code anyway because i'm bored.
*
* Also should not that using a AutoHotKey or any other macro program is way
* easier but i'm using Java because learning amiright
*/
//declaring variables and objects
private static String fileName = "C:/users/21cra/Desktop/rmtinfo.txt";
private static Scanner SC;
private Robot robObject;
public static void main(String[] args) {
//creates JFrame
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
Main frame = new Main();
frame.setTitle("Copier");
frame.setResizable(false);
frame.setSize(0, 0);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
public Main() {
//add key listener for this JFrame
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
// try catch for forcing Escape key press
try {
robObject = new Robot();
robObject.keyPress(KeyEvent.VK_ESCAPE);
robObject.keyRelease(KeyEvent.VK_ESCAPE);
System.out.println("press");
} catch (AWTException e1) {
e1.printStackTrace();
}
}
@Override
public void keyPressed(KeyEvent e) {
// declaring variables and objects
String pass = null;
File passFile = new File(fileName);
// try catch for handling next key press
// also copies the first line of any file
try {
SC = new Scanner(new File(fileName));
pass = SC.next();
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_ESCAPE) {
StringSelection stringObj = new StringSelection(pass);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringObj, null);
System.exit(0);
}
System.out.println(pass);
} catch (Exception error) {
System.out.println("Error " + error);
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
}
【问题讨论】:
-
KeyListener将需要它注册的组件具有焦点和可聚焦性。JFrame是一个组件组件,因此不同的层可能会“窃取”焦点,使其难以使用。在您的示例中,您尝试在窗口实现并处于活动状态之前发送击键,因此您可以考虑使用第二个线程来发送击键 -
@MadProgrammer 如何为这个问题创建第二个线程?我不熟悉这个概念,还在学习中。
标签: java jframe keylistener keyevent