Loss of Focus of a jTextField

3

I need to convert from inches to centimeters and vice versa. The idea is to have a single button "convert" and that according to the field that has just lost focus, I will see the conversion in the other JtextField the result.

Example: I wrote a value in the field centimeters, and it has to appear in the field inches, and the same thing if I work the other way around.

The problem is that I can not do it by asking in the action performed of Jbutton the condition if(CampoPulgadas.isFocusOwner) .

I would appreciate the help.

private void ConvertirBotonActionPerformed(java.awt.event.ActionEvent evt) {                                               

    double convertido = 0;

    if(!CampoCentimetros.isFocusOwner())
    {
        String cen = CampoCentimetros.getText();

        try{
            convertido = Double.parseDouble(cen);
        }
        catch(NumberFormatException ex){
            JOptionPane.showMessageDialog(this, "El valor "+convertido+" no es válido!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }

        convertido /= 2.54;

        cen = String.format("%.4f",convertido);

        CampoPulgadas.setText(cen);

        return;
    }
    if(CampoPulgadas.isFocusOwner())
    {
    } else {
        String pulg = CampoPulgadas.getText();

        try{
            convertido = Double.parseDouble(pulg);
        }
        catch(NumberFormatException e){

            JOptionPane.showMessageDialog(this, "El valor "+convertido+" no es válido!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }

        convertido *= 2.54;

        pulg = String.format("%.4f", convertido);

        CampoCentimetros.setText(pulg);

        return;
    }
}                                   
    
asked by Matias R. 17.04.2016 в 22:01
source

2 answers

3

If the component has the focus, then when invoking the isFocusOwner method on that instance (the component), it will return true . When you click on the "Convert" button, this is the owner of the focus, unless it is not focusable . 1

Hence, a possible solution is to make ConvertirBoton not focusable . That is:

ConvertirBoton.setFocusable(false);

Thus, just after writing or doing something in any of the text fields and clicking with the mouse, the text field will not lose focus. 2

──────────────
1. See more details of this in How to Use the Focus Subsystem .
2. The only drawback with this solution is that you can not use the keyboard to press the button, only with the mouse.

    
answered by 17.04.2016 / 23:15
source
1

You can add a FocusListener to the fields so that when they lose focus convert the amount.

I would even recommend using a KeyListener so the amount would be converted as you type.

    
answered by 18.04.2016 в 00:31