Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Text with number in TextField

I have this field in which I insert port number. I would like to convert the string automatically into number:

fieldNport = new TextField();
    fieldNport.setPrefSize(180, 24);
    fieldNport.setFont(Font.font("Tahoma", 11));
    grid.add(fieldNport, 1, 1);

Can you tell how I can do this? I cannot find suitable example in stack overflow.

EDIT:

Maybe this:

 fieldNport.textProperty().addListener(new ChangeListener()
        {
            @Override
            public void changed(ObservableValue o, Object oldVal, Object newVal)
            {
                try
                {
                    int Nport = Integer.parseInt((String) oldVal);
                }
                catch (NumberFormatException e)
                {

                }
            }
        });
like image 332
Peter Penzov Avatar asked Feb 06 '26 21:02

Peter Penzov


2 Answers

Starting with JavaFX 8u40, you can set a TextFormatter object on a text field:

UnaryOperator<Change> filter = change -> {
    String text = change.getText();

    if (text.matches("[0-9]*")) {
        return change;
    }

    return null;
};
TextFormatter<String> textFormatter = new TextFormatter<>(filter);
fieldNport = new TextField();
fieldNport.setTextFormatter(textFormatter);

This avoids both subclassing and duplicate change events that you will get when you add a change listener to the text property and modify the text in that listener.

like image 103
Uwe Avatar answered Feb 12 '26 16:02

Uwe


You can write something like this :

fieldNPort.text.addListener(new ChangeListener(){
        @Override public void changed(ObservableValue o,Object oldVal, Object newVal){
             //Some Code
             //Here you can use Integer.parseInt methods inside a try/catch 
             //because parseInt throws Exceptions
        }
      });

Here are all the things you'd need about properties and Listeners in JavaFX:
http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm
If you have any question, I'll be glad to help.

like image 36
Fabinout Avatar answered Feb 12 '26 17:02

Fabinout