Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seprating the digits in the textfiled while entering the numbers (Javafx)

I created a simple javafx program. I want to seprate the digits three by three when I entering the digits in the textfiled. I used two solution which are given in the stackoverflow links(How to format text of TextField? JavaFX , Java 8 U40 TextFormatter (JavaFX) to restrict user input only for decimal number)

but none them are working for me. the first solution(set textformatter) was useless for me(or maybe I couldn't work with it in a right way) but the second one was working but only accept 4 digits and the other numbers that I enterd in the textfield are the in the same style that I enterd them without comma.

I want to seprate every three digits like this: 12,564,546,554 if anyone know the solution please help me to overcome this problem. thanks.

 import javafx.application.Application;
 import javafx.scene.Scene;
 import javafx.scene.control.TextField;
 import javafx.scene.control.TextFormatter;
 import javafx.scene.layout.HBox;
 import javafx.stage.Stage;

 import java.text.DecimalFormat;
 import java.text.ParsePosition;


 public class DelimiterExample extends Application{


public static void main(String[] args) {
    launch(args);
}


@Override
public void start(Stage primaryStage) throws Exception {

    TextField textField = new TextField();
    HBox hBox = new HBox();

    //solution one

    DecimalFormat format = new DecimalFormat( "#,###" );

    textField.setTextFormatter( new TextFormatter<>(c ->
    {
        if ( c.getControlNewText().isEmpty() )
        {
            return c;
        }

        ParsePosition parsePosition = new ParsePosition( 0 );
        Object object = format.parse( c.getControlNewText(), parsePosition );

        if ( object == null || parsePosition.getIndex() < c.getControlNewText().length() )
        {
            return null;
        }
        else
        {

            return c;
        }

    }));


    // solution two

    textField.textProperty().addListener((obs , oldVal , newVal)-> {

        if (newVal.matches("\\d*")) {
            DecimalFormat formatter = new DecimalFormat("#,###");
            String newvalstr = formatter.format(Float.parseFloat(newVal));
            //System.out.println(newvalstr);
            textField.setText(newvalstr);
        }


    });

    hBox.getChildren().add(textField);
    Scene scene = new Scene(hBox , 100 , 100);
    primaryStage.setScene(scene);
    primaryStage.show();
}
}
like image 754
Sameer Avatar asked Jan 27 '26 19:01

Sameer


2 Answers

Please guys don't reinvent the wheel. The class javafx.util.converter.NumberStringConverter do all the needed work for us:

TextField numberField = new TextField();
TextFormatter<Number> textFormatter = new TextFormatter<>(new NumberStringConverter());
numberField.setTextFormatter(textFormatter);

NumberStringConverter is your friend ;), if you want to listen the correct number changes on the textfield, simply use the next textFormatter property (forgive direct method invocations over the textField object):

textFormatter.valueProperty(); //Returns ObjectProperty<Number>

Then you can retrieve any kind of number subclass (number.intValue(), number.floatValue(), etc), and the ChangeListener only will be triggered when the user writes a valid numeric value.

If you want to manually set a number value to the textfield:

float value = 1000f; //or any type of Number subclass
textFormatter.setValue(value);

P.D: NumberStringConverter has a Locale attribute that can be changed to apply the appropriate format of the desired Country.

like image 140
GaRzY Avatar answered Jan 30 '26 10:01

GaRzY


Any modification that is not a selection change can be fixed by modifying the chars before the range:

final char seperatorChar = ',';
final Pattern p = Pattern.compile("[0-9" + seperatorChar + "]*");
textField.setTextFormatter(new TextFormatter<>(c -> {
    if (!c.isContentChange()) {
        return c; // no need for modification, if only the selection changes
    }
    String newText = c.getControlNewText();
    if (newText.isEmpty()) {
        return c;
    }
    if (!p.matcher(newText).matches()) {
        return null; // invalid change
    }

    // invert everything before the range
    int suffixCount = c.getControlText().length() - c.getRangeEnd();
    int digits = suffixCount - suffixCount / 4;
    StringBuilder sb = new StringBuilder();

    // insert seperator just before caret, if necessary
    if (digits % 3 == 0 && digits > 0 && suffixCount % 4 != 0) {
        sb.append(seperatorChar);
    }

    // add the rest of the digits in reversed order
    for (int i = c.getRangeStart() + c.getText().length() - 1; i >= 0; i--) {
        char letter = newText.charAt(i);
        if (Character.isDigit(letter)) {
            sb.append(letter);
            digits++;
            if (digits % 3 == 0) {
                sb.append(seperatorChar);
            }
        }
    }

    // remove seperator char, if added as last char
    if (digits % 3 == 0) {
        sb.deleteCharAt(sb.length() - 1);
    }
    sb.reverse();
    int length = sb.length();

    // replace with modified text
    c.setRange(0, c.getRangeEnd());
    c.setText(sb.toString());
    c.setCaretPosition(length);
    c.setAnchor(length);

    return c;
}));
like image 40
fabian Avatar answered Jan 30 '26 10:01

fabian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!