[英]KeyListener not responding to keyboard input
I've been trying to learn more advanced java on my own (My class is only covering text files) and I'm stumped on the using KeyListener. 我一直在尝试自己学习更高级的java(我的类只覆盖文本文件)而且我对使用KeyListener感到困惑。 I managed to get it to work in another program, but I can't find the problem here.
我设法让它在另一个程序中工作,但我在这里找不到问题。 No errors show up on the console.
控制台上没有错误显示。 This program uses a robot to type predefined Strings in a text file.
该程序使用机器人在文本文件中键入预定义的字符串。 Here's the main class.
这是主要课程。
import java.awt.AWTException;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.SwingUtilities;
public class FileTyper implements KeyListener {
static Keyboard kb;
static Scanner infile;
static boolean on = false;
static Window window;
public static void main(String args[]) throws AWTException, FileNotFoundException{
init();
start();
}
private static void init() throws AWTException, FileNotFoundException{
window = new Window();
kb = new Keyboard();
kb.setSpeed(50);
infile = new Scanner(new File("C:/Users/Ali/Desktop/input.txt"));
}
private static void start(){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if(on && infile.hasNext()){
String temp = infile.nextLine();
kb.type(temp);
kb.type("\n");
}
}
});
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_F9:
System.out.println("CONSOLE: Starting");
on = true;
break;
case KeyEvent.VK_F10:
System.out.println("CONSOLE: Stopping");
on = false;
break;
}
}
@Override
public void keyTyped(KeyEvent e) {
}
} }
Not related to your problem, but don't use static methods and variables. 与您的问题无关,但不要使用静态方法和变量。 This indicates a poor design.
这表明设计不佳。
If the KeyListener doesn't work then your component probably doesn't have focus. 如果KeyListener不起作用,那么您的组件可能没有焦点。
Also, you actually need to add the KeyListener to your component. 此外,您实际上需要将KeyListener添加到组件中。 Start by reading the Swing tutorial on How to Write a Key Listener .
首先阅读关于如何编写密钥监听器的Swing教程。 The example should help you out and also show you a better way to design your program so you don't use static everywhere.
该示例应该可以帮助您,并向您展示设计程序的更好方法,这样您就不会在任何地方使用静态。
addKeyListener(...)
. addKeyListener(...)
将其添加到组件中。 You don't do this, and it won't work unless it has a chance to. Edit 编辑
You state: 你说:
What if I wanted to use KeyListener when the program window is minimized?
如果我想在程序窗口最小化时使用KeyListener,该怎么办?
I mean use a shortcut key to pause the start or stop the program我的意思是使用快捷键来暂停启动或停止程序
Core Java by itself cannot do this. 核心Java本身无法做到这一点。 For this to work, you either need to augment Java with JNI or JNA or use an OS-specific utility program.
为此,您需要使用JNI或JNA扩充Java或使用特定于操作系统的实用程序。 I've used AutoIt for my Windows apps.
我已经将AutoIt用于我的Windows应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.