mpp94
mpp94

Reputation: 23

Java Swing how to define multiple focus listeners on JTextFields but with different button actions

I am making JTextFields which should be populated when click on a button.

Suppose for an example:

     txtField1.addFocusListener(new FocusListener() {
            JTextField field = txtField1;
            @Override
            public void focusGained(FocusEvent e) {
                btnMain_0.addActionListener(ee -> {

                    if (field.getText().length() > 4)
                        return;
                    else
                        field.setText((field.getText() + "0"));
                });

            }

            @Override
            public void focusLost(FocusEvent e) {
            
            }
        });




 txtField2.addFocusListener(new FocusListener() {
            JTextField field = txtField2;
            @Override
            public void focusGained(FocusEvent e) {
                btnMain_0.addActionListener(ee -> {

                    if (field.getText().length() > 4)
                        return;
                    else
                        field.setText((field.getText() + "0"));
                });

            }

            @Override
            public void focusLost(FocusEvent e) {
            
            }
        });

But if I click on txtField1 and press btnMain_0, it enter 0. Then if I click on txtField2 and press btnMain_0, it enter 00 (it considered pressing btnMain_0 two times).

How I can make it? Is there better solution two run listeners from list of jtextfields?

Upvotes: 0

Views: 163

Answers (1)

camickr
camickr

Reputation: 324197

You can define a custom TextAction and add it to your buttons.

The TextAction allows you to track the last text component that had focus (before you click on the button).

Something like:

class KeyboardAction extends TextAction
{
    private String letter;

    public KeyboardAction(String letter)
    {
        super(letter);
        this.letter = letter;
    }

    public void actionPerformed(ActionEvent e)
    {
        JTextComponent component = getFocusedComponent();
        component.setCaretPosition( component.getDocument().getLength() );
        component.replaceSelection( letter );
    }
}

You then use the class like:

jButton1 = new JButton( new KeyboardAction("1") );
jButton2 = new JButton( new KeyboardAction("2") );

or you add the Action to an existing button by using:

button.setAction( new KeyboardAction("1") );

Upvotes: 1

Related Questions