ardayigit ardayigit - 4 months ago 33
Java Question

JAVA - KeyListener with JFormattedTextField

Can someone explain to me why the

getValue()
function returns
null
always? If I use
getText()
instead of
getValue()
then everything is perfect, but what I want is the value and not the text. I can convert it to an integer, but I don't think that this is the best way.

public class Test {
public static void main(String[] args) {

JFrame jf = new JFrame("test jftf");
jf.setSize(100, 100);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
JFormattedTextField jftf = new JFormattedTextField(NumberFormat.getIntegerInstance());
jftf.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}

@Override
public void keyPressed(KeyEvent e) {
}

@Override
public void keyReleased(KeyEvent e) {
System.out.println(jftf.getValue());
}

});
jf.add(jftf);
}

}

Answer

If you are relying on the getValue() method, you need to make sure that current edits have been committed. You can do this by calling the the method commitEdit() otherwise you may not get the values you are expecting:

@Override
public void keyReleased(KeyEvent e) {
    //Forces the current value to be taken from the AbstractFormatter 
    //and set as the current value:
    try {
        jftf.commitEdit();
    } catch (ParseException e1) {
        //Handle possible parsing error...
    }
    System.out.println(jftf.getValue()); 
}
Comments