Search code examples
javaswingtextboxactionlistenerkeypad

How to Select a Textbox on Click to Input Keypads Output


Interface

https://i.sstatic.net/cAvOJ.png

Above image shows the interface i am trying to implement. log in panel and keypad panel need to somehow work together, so whenever i click on the selected text box i can use the keypad to enter the required input.

On correct detail entry the log in panel will change to another panel with other text boxes so the keypad will have to work with these too.

Any ideas ? Thank you in advance!


Solution

  • You can extend TextAction to create an Action to be shared by each button. The TextAction allows you to access the last focused text component:

    Action numberAction = new TextAction()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            JTextComponent input = getFocusedComponent();
            input.replaceSelection(e.getActionCommand());
        }
    };
    
    JButton button1 = new JButton("1");
    button1.addActionListener( numberAction );
    JButton button2 = new JButton("2");
    button2.addActionListener( numberAction );
    ...
    

    You would need to create a separate Action for the "Clear" button.