Como eu posso fazer o campo exibir 0,0000 por exemplo ? Por padrão ele só seta 2 casas, não estou conseguindo aumentar.
Exemplo:
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.*;
import java.math.BigDecimal;
public class CampoMonetario extends TextField {
public CampoMonetario() {
setValor("0,00");
//setStyle("-fx-text-fill: red;");
lengthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
String value = getText();
value = value.replaceAll("[^0-9]", "");
value = value.replaceAll("([0-9]{1})([0-9]{14})$", "$1.$2");
value = value.replaceAll("([0-9]{1})([0-9]{11})$", "$1.$2");
value = value.replaceAll("([0-9]{1})([0-9]{8})$", "$1.$2");
value = value.replaceAll("([0-9]{1})([0-9]{5})$", "$1.$2");
value = value.replaceAll("([0-9]{1})([0-9]{2})$", "$1,$2");
setText(value);
textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
if (newValue.length() > 16) {
setText(oldValue);
}
if (newValue.length() > 4) {
if (newValue.substring(0, 1).contains("0")) {
setText(newValue.substring(0, 1).replace("0", "") + getText().substring(1, getText().length()));
} else if (newValue.substring(0, 2).contains("0.")) {
setText(newValue.substring(0, 1).replace("0", "") + getText().substring(1, getText().length()));
}
}
}
});
}
});
focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observableValue, Boolean out, Boolean in) {
if ((new BigDecimal(getValor() + "0")).compareTo(BigDecimal.ZERO) <= 0 && in) {
setText("");
} else if (getText().equals("") && out) {
setText("0,00");
}
final int length = (getText().length());
if (length > 0 && length < 4) {
setText(getText() + "00");
lengthProperty();
}
}
});
}
public void setValor(Object valor) {
if (!(valor + "").contains("nul")) {
setText(String.valueOf(valor).replace(".", ",").replace("", ""));
requestFocus();
} else {
setText("0,00");
}
}
public BigDecimal getValor() {
return ((!getText().isEmpty()) ? new BigDecimal(getText().replace(".", "").replace(",", ".")) : BigDecimal.ZERO.setScale(2));
}
}