addKeyListener有什么选择

时间:2013-12-22 02:24:27

标签: java swing add keylistener

我想添加一个KeyListener并让它只附加到程序本身,这样我的程序就可以在没有任何窗口的情况下获取输入。我想让它在后台运行并更改键的一些功能。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

试一试。我想你想使用键绑定而不是KeyListener。请参阅下面的代码。我已将四个箭头键绑定到不同的操作。看看How to use Key Bindings

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class KeyBindings extends JPanel {
    public KeyBindings(){
        Action upAction = new AbstractAction(){
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Down Arrow Pressed");
            }
        };
        Action downAction = new AbstractAction(){
            @Override
            public void actionPerformed(ActionEvent e) {
               System.out.println("Down Arrow Pressed");
            }
        };
        Action leftAction = new AbstractAction(){
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Left Arrow Pressed");
            }
        };
        Action rightAction = new AbstractAction(){
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Right Arrow Pressed");
            }
        };


        getInputMap().put(KeyStroke.getKeyStroke("UP"), "upAction");
        getActionMap().put("upAction", upAction);
        getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "downAction");
        getActionMap().put("downAction", downAction);
        getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "leftAction");
        getActionMap().put("leftAction", leftAction);
        getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "rightAction");
        getActionMap().put("rightAction", rightAction);
    }

    public Dimension getPreferredSize(){
        return new Dimension(300, 300);
    }

    public static void createAndShowGui(){
        JFrame frame = new JFrame();
        frame.add(new KeyBindings());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                createAndShowGui();
            }
        });
    }
}

答案 1 :(得分:0)

您必须自动为自己的应用提供服务,然后点击here for help