Amundeep Singh
Amundeep Singh

Reputation: 194

Set keyboard shortcut for a JButton?

I have a type game in which you have to type the words that appear as fast as possible before the time limit runs out, but every time you type a word, you must move the mouse and click enter and click back into the user input to type the next word. I was just hoping if there was way to use "keyCode.VK_Enter" to issue an Action Command called by the JButton.

Some snippets of my code:

The Enter button and user input and output:

enter = new JButton("Enter");
    enter.setFont(serif);  //serif is specified earlier
    enter.setActionCommand("Enter");
    enter.addActionListener(this);
    container.add(enter);

userOutput = new JTextField(50);
    userOutput.setFont(serif);
    container.add(userOutput);
    userOutput.setEditable(false);

userInput = new JTextField(43);
    userInput.setFont(serif);
    container.add(userInput);
    userInput.setEditable(false);

The actionPerformed method getting the enter button's action command:

if(userInput.getText().equals(userOutput.getText())){
            userInput.setText("");
            score += 100;

Upvotes: 0

Views: 1189

Answers (1)

Katana
Katana

Reputation: 755

Why don't you just add an actionlistener to the JTextField (which would be triggered when the user hits enter).

userInput.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
        // Do something
    }

});

Upvotes: 5

Related Questions