1

我一直在尝试自己学习更高级的 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) {

}

}

4

2 回答 2

2
  • For a KeyListener to work, you must first add it to a component via addKeyListener(...). You don't do this, and it won't work unless it has a chance to.
  • As camickr notes, a KeyListener requires that the component it listens to has focus.
  • Usually it's better not to use KeyListeners in Swing apps but to use Key Bindings.
  • Shoot, you don't even have a visible GUI of any kind at all, so you really need to do more studying of the tutorials to first get your gui up and running before even considering adding a KeyListener or use Key Bindings.

Edit
You state:

What if I wanted to use KeyListener when the program window is minimized?
I mean use a shortcut key to pause the start or stop the program

Core Java by itself cannot do this. For this to work, you either need to augment Java with JNI or JNA or use an OS-specific utility program. I've used AutoIt for my Windows apps.

于 2013-10-19T19:28:34.017 回答
2

与您的问题无关,但不要使用静态方法和变量。这表明设计不佳。

如果 KeyListener 不起作用,那么您的组件可能没有焦点。

此外,您实际上需要将 KeyListener 添加到您的组件中。首先阅读有关如何编写 Key Listener的 Swing 教程。该示例应该可以帮助您,并向您展示设计程序的更好方法,这样您就不会在任何地方使用静态。

于 2013-10-19T19:26:19.650 回答