Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
992 views
in Technique[技术] by (71.8m points)

swing - Java KeyListener vs Keybinding

i am trying to write a calculator and having a problem. I already made a actionlistener for all buttons and now i want to make it possible to input data from keyboard. DO i need to do the whole thing for KeyListener or Keybinding or is there any other a way to make that after clicking a button it will be sent to the instructions in actionlistener? And whats better:Keylistener or Keybinding

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Generally speaking, where you have a limited set of key inputs, key bindings are a better choice.

KeyListener suffers from issues related to focusability and with other controls in the GUI, focus will constantly be moving away from the component (with the KeyListener) all the time.

A simple solution would be to use the Actions API. This allows you to define a self contained "action" which acts as a ActionListener but also carries configuration information that can be used to configure other UI components, in particular, buttons

For example...

Take a generic NumberAction which could represent any number (lets limit it to 0-9 for now)...

public class NumberAction extends AbstractAction {

    private int number;

    public NumberAction(int number) {
        putValue(NAME, String.valueOf(number));
    }

    public int getNumber() {
        return number;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int value = getNumber();
        // Do something with the number...
    }

}

You could do something like...

// Create the action...
NumberAction number1Action = new NumberAction(1);
// Create the button for number 1...
JButton number1Button = new JButton(number1Action);

InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
// Create a key mapping for number 1...
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), "number1");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD1, 0), "number1");

ActionMap am = getActionMap();
// Make the input key to the action...
am.put("number1", number1Action);

And you're done...

You can also create any number of instance of the NumberAction for the same number, meaning you could configure the UI and the bindings separately, but know that when triggered, they will execute the same code logic, for example...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...