Search code examples
javakeypressactionlistenerkeyevent

JAVA - Creating a KeyPress Event During a Button Action Listener click event


I am creating a java Sudoku GUI application at the moment.

The grid for showing the Sudoku puzzle is simply a 2 dimensional array of myJButtons(implementing JButton) - for this problem they can be treated as regular JButtons.

The program will allow a button in the grid to be clicked, calling an actionlistener.

Is there a way to allow for a KeyAdapter Keypress to be created when a button is clicked to allow for a number press - physical key 1,2,3,4,5,6,7,8,9,0

I would like the action listener to work only for when a button is clicked.

A simpler example of this would be a Frame with a single button. when the button is pressed, the user can press a physical key on the keyboard, setting the jbutton text to the key value. Additional key presses would not change the button text, unless the button is clicked first.

class ClickAction implements ActionListener { // Action Listener called when button is Pressed

    public void actionPerformed(ActionEvent ae) {

        //need a way to create a keyevent listener here

    }
}

Thanks In advance to anyone who can answer this!


Solution

  • I would use another solution. Instead of creating KeyEvent Listeners every time a Button is clicked, you could register the key listener during the start up of the application. Then you can use a flag to check if the button was clicked first. Only if this flag is true, you perform the actions in the KeyEvent listener. Otherwise you skip all statements in the KeyEvent Listener.

    Here an example:

    public class TestClass {
    
        private boolean isButtonClicked = false;
    
        public void testYourButtons() {
    
            JButton myButton = new JButton();
            myButton.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    isButtonClicked = !isButtonClicked;
                }
            });
    
            myButton.addKeyListener(new KeyListener() {
    
                @Override
                public void keyTyped(KeyEvent arg0) {
                    // TODO Auto-generated method stub  
                }
    
                @Override
                public void keyReleased(KeyEvent arg0) {
                    // TODO Auto-generated method stub
                }
    
                @Override
                public void keyPressed(KeyEvent arg0) {
                    if (isButtonClicked) {
                        // TODO Do here your event handling
                        isButtonClicked = false;
                    }
                }
            });
    
        }
    
    }