我一直在尝试自己学习更高级的 java(我的课程只涵盖文本文件),但我对使用 KeyListener 感到困惑。我设法让它在另一个程序中工作,但我在这里找不到问题。控制台上没有显示错误。该程序使用机器人在文本文件中键入预定义的字符串。这是主要课程。
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) {
}
}