Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

336
Views
JavaFX: How to bind text field "style property" to text property matching some pattern

In my application I have a screen with three fields which I need to validate, and a Save button.

I bind save button "disable property" to fields' "text property" matching some pattern (simplified patterns in this example, doesn't matter):

public void initialize(){
    saveNetworkBtn.disableProperty()
            .bind(textPropertyBindingPattern(ipInp, Pattern.compile("[0-9]{3}"))
                    .or(textPropertyBindingPattern(subnetInp, Pattern.compile("[0-9]{3}")))
                    .or(textPropertyBindingPattern(gatewayInp, Pattern.compile("[0-9]{3}"))));
}

private BooleanBinding textPropertyBindingPattern(TextField textField, Pattern pattern ) {
    return Bindings.createBooleanBinding(() ->
            !pattern.matcher(textField.getText()).matches(), textField.textProperty());
}

So that save button is locked until all values are correct:enter image description here

But I need to highlight incorrect fields also with some red border like

-fx-border-color: red;

enter image description here

My main goal is to handle this in one place instead of adding several listeners. Is it possible to bing this somehow in the code above or I need to add listeners to each field?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Solved by adding a listener to binding, which adds a style to received text field:

private BooleanBinding textPropertyBindingPattern(TextField textField, Pattern pattern) {
    BooleanBinding binding = Bindings.createBooleanBinding(() ->
            !pattern.matcher(textField.getText()).matches(), textField.textProperty());

    applyValidationClass(textField, binding.get());

    binding.addListener((obs, oldValue, newValue) -> {
        applyValidationClass(textField, newValue);
    });
    return binding ;
}

private void applyValidationClass(TextField textField, boolean isInvalid) {
    textField.pseudoClassStateChanged(PseudoClass.getPseudoClass("incorrect-value"), isInvalid);
}

and 'incorrect-value' described in CSS file:

TextField:incorrect-value {
    -fx-border-color: red;
}

Visualisation: https://www.screencast.com/t/4NKEjjopvaE7

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!