Search code examples
javaswingdoublejtextfield

How can I make a JTextField accept double value with comma as the separator?


Title says it all. I get NumberFormatException for obvious reason. I want to input double values to my JTextFields with using comma instead of a dot as the decimal separator since I'm north European.

public void actionPerformed(ActionEvent event2) {

    NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);

    double firstW = Double.parseDouble(firstWeight.getText());
    double secondW = Double.parseDouble(secondWeight.getText());

    double outcome = (firstW - secondW);

    nf.setMaximumFractionDigits(2);
    JLabel result = new JLabel();
    result.setText(nf.format(outcome) +" kg" );

    add(result);
    setVisible(true);

}

Solution

  • If you have a NumberFormat you already have all you need. Just use NumberFormat.parse instead of Double.parse. But it’s even easier when you use a JFormattedTextField (guess what it does from the class name. Pass the desired NumberFormat to the constructor, i.e. new JFormattedTextField(nf). The JFormattedTextField has a getValue method which returns the last valid edit, in case of your NumberFormat it will be a Number.

    Know your libraries