2017-01-18 1 views
2

javaFX 텍스트 필드를 소수점 두 자리까지 설정하고 싶습니다. 대답을 찾았지만 숫자 값입니다. e-gjavafx textField 청취자를 소수 2 자리까지 추가

// force the field to be numeric only 
textField.textProperty().addListener(new ChangeListener<String>() { 
    @Override 
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { 
     if (!newValue.matches("\\d*")) { 
      textField.setText(newValue.replaceAll("[^\\d]", "")); 
     } 
    } 
}); 

위의 코드에서 한계 값을 10 진수로 대체하는 것은 무엇입니까? 또는 textField를 제한하는 다른 솔루션이 있습니까?

@FXML public TextField InvoiceTotal; 

private DoubleProperty invTotal; 
invTotal = new SimpleDoubleProperty(0); 

netAmount.bind(grossAmount.subtract(disc)); 

StringConverter<? extends Number> converter= new DoubleStringConverter(); 

Bindings.bindBidirectional(InvoiceTotal.textProperty(),invTotal,(StringConverter<Number>)converter); 

내가 여기에 바인딩 텍스트 필드가 내 부분적인 코드는이 ... 지금은 InvoiceTotal의 텍스트 필드

+2

TextFormatter를 살펴보십시오. UnaryOperator로 모든 것을 정의 할 수 있습니다. –

답변

2

를 사용하여 텍스트 필드에 텍스트 포맷터에 두 개의 소수 제한을 설정합니다. 패턴은 소수점 이하 두 자리까지 가능한 모든 십진수 값을 일치시켜야합니다. (선택적 음수 부호 다음에 임의의 숫자가오고, 선택적으로 소수점과 0-2 자리가 따라옵니다.) 텍스트 형식화 프로그램이 결과 텍스트가 해당 패턴과 일치하면 변경 사항을 승인하고 그렇지 않으면 거부합니다.

import java.util.function.UnaryOperator; 
import java.util.regex.Pattern; 

import javafx.application.Application; 
import javafx.geometry.Insets; 
import javafx.scene.Scene; 
import javafx.scene.control.TextField; 
import javafx.scene.control.TextFormatter; 
import javafx.scene.control.TextFormatter.Change; 
import javafx.scene.layout.StackPane; 
import javafx.stage.Stage; 

public class DecimalTextField extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     Pattern decimalPattern = Pattern.compile("-?\\d*(\\.\\d{0,2})?"); 

     UnaryOperator<Change> filter = c -> { 
      if (decimalPattern.matcher(c.getControlNewText()).matches()) { 
       return c ; 
      } else { 
       return null ; 
      } 
     }; 

     TextFormatter<Double> formatter = new TextFormatter<>(filter); 

     TextField textField = new TextField(); 
     textField.setTextFormatter(formatter); 
     StackPane root = new StackPane(textField); 
     root.setPadding(new Insets(24)); 

     primaryStage.setScene(new Scene(root)); 
     primaryStage.show(); 
    } 

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

TextField에 바인딩이 있습니다. UnaryOperator가 작동하지 않습니다. –

+0

Property listner에 적용 할 패턴이 있습니까? –

+0

지난 두 개의 설명을 이해할 수 없습니다. 귀하의 질문에 해당 정보를 포함 시키려면 [편집]하십시오. 텍스트 필드의 텍스트가 뭔가에 바인딩되어 있으면 사용자가 입력 할 수 없습니다. –

0

저항 할 수 없었습니다. 이것은 두 줄의 대답을 모두 폐합니다 (모든 작업을 수행하는 답).

private static TextFormatter<Double> new3DecimalFormatter(){ 
     Pattern decimalPattern = Pattern.compile("-?\\d*(\\.\\d{0,3})?"); 
     return new TextFormatter<>(c -> (decimalPattern.matcher(c.getControlNewText()).matches()) ? c : null); 
} 
관련 문제