Search code examples
javaswingjbuttonjtextfield

Insert text to selected JTextfield using JButtons


I have multiple text fields and buttons

Textfields buttons

When a text field is selected, text should be added to it when a button is pressed.

This is how I tried

import javax.swing.text.JTextComponent;
    private void num9ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            JTextComponent component = getFocuedComponent();
            component.setText( component.getText() + "9" );

    }

But it didn't work for me.

PS. Trying to make Matrix Calculator.

EDIT : for reference ... this how i implemented it ... after SJuan76's answer .... thanks!!

private JTextComponent selectedTextField;

// TextFields onFocus event
    private void a33FocusGained(java.awt.event.FocusEvent evt) {
        selectedTextField = (JTextComponent) evt.getSource();
    }
// action for button
        private void num9ActionPerformed(java.awt.event.ActionEvent evt) {                                            
                selectedTextField.setText( selectedTextField.getText() + "9" );

        }

Solution

  • You don't specify the problem so I'll make a guess. If you want a better answer give a better question.

    When you click in the button, the focus of the inputtext has already been lost (transferred to that button).

    Add a listener to the text fields that update a shared variable, pointing to the last output text that was selected. When you process the actionevent, update that component.

    Of course, there is the issue of resetting the shared variable when it no longer has sense.

    UPDATE: I thought getFocusedComponent() was part of the API but I cannot find any reference to it, you should post more code if you want a good answer.