Sparker0i Sparker0i - 2 months ago 5
Java Question

Have Focus on one JTextField and perform an action related to it

My Application has two JTextField's and one JButton.

I want a code snippet where in


  • If the first TextField is focussed/selected, the button will set its TextField (using setText method) to 1,

  • If the second TextField is focussed/selected, the button will set its TextField (using setText method) to 1



EDIT : What I am trying to do (numInput , denInput are both JTextFields)

public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (numInput.isFocusOwner()) {
if (s.equals("1")) {
if (z == 0) {
numInput.setText(numInput.getText() + "1");
} else {
numInput.setText("");
numInput.setText(numInput.getText() + "1");
z = 0;
}
}
else if (denInput.isFocusOwner()) {
if (s.equals("1")) {
if (z == 0) {
denInput.setText(numInput.getText() + "1");
} else {
denInput.setText("");
denInput.setText(numInput.getText() + "1");
z = 0;
}
}
}


This never works for me.

Answer

Create an Action that extends TextAction and add this Action to your button.

TextAction has a getFocusedComponent() method that will return the last text component that had focus.

The basic code for the Action would be:

TextAction action = new TextAction("")
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
            JTextComponent textField = getFocusedComponent();
            System.out.println( textField.getText() );
    }
};

This will only work if you only have two text field on the form. If you have more than two then you would need to add extra code to verify that focus was on either of the two text fields before the button was clicked.