简体   繁体   中英

How to shorten this KeyListener code

I am using this code to detect when the user presses an arrow key in my program. I need which arrow key was pressed to be sent to a method which will process it and do what it needs to do. It's working, but the problem is my code is stupidly long and repetitve, and I'm sure theres a way to shorten this. I can pass integers 0-3 instead of strings if it makes doing this easier. This is my code right now:

getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); 
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right");
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "up");
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "down");
getRootPane().getActionMap().put("left", new AbstractAction(){
    public void actionPerformed(ActionEvent e)
    {
        close("left");
    }
});
getRootPane().getActionMap().put("right", new AbstractAction(){
    public void actionPerformed(ActionEvent e)
    {
        close("right");
    }
});
getRootPane().getActionMap().put("up", new AbstractAction(){
    public void actionPerformed(ActionEvent e)
    {
        close("up");
    }
});
getRootPane().getActionMap().put("down", new AbstractAction(){
    public void actionPerformed(ActionEvent e)
    {
        close("down");
    }
});

Abstract the common functionality into a method:

private void mapKey(String keyStroke, final String command) {
    Action action = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            close(command);
        }
    };
    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(KeyStroke.getKeyStroke(keyStroke), action);
    getRootPane().getActionMap()
        .put(action, action);
}

And then you can do:

mapKey("LEFT",  "left");
mapKey("RIGHT", "right");
mapKey("UP",    "up");
mapKey("DOWN",  "down");

Create an inner class which extends AbstractAction and can obtain the string parameter

something like this

private class CloseAction extends AbstractAction {
    private final String action;
    public CloseAction(String anAction) {
        action = anAction;
    }

    public void actionPerformed(ActionEvent e) {
        close(action);
    }
}

and then:

getRootPane().getActionMap().put("up", new CloseAction("up"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM