【发布时间】:2018-11-15 06:14:18
【问题描述】:
我创建了一个简单的 javafx 程序。当我在文本文件中输入数字时,我想将数字三三分开。我使用了stackoverflow链接中给出的两个解决方案(How to format text of TextField? JavaFX,Java 8 U40 TextFormatter (JavaFX) to restrict user input only for decimal number)
但他们都没有为我工作。第一个解决方案(设置 textformatter)对我来说没用(或者我可能无法以正确的方式使用它)但第二个解决方案正在工作但只接受 4 位数字,而我在文本字段中输入的其他数字是与我输入它们的样式相同,不带逗号。
我想像这样分隔每三个数字:12,564,546,554 如果有人知道解决方案,请帮助我克服这个问题。 谢谢。
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();
}
}
【问题讨论】:
-
你想要逗号之间的数字,对吧?你试过
String.split(String)使用","作为参数吗? -
没有。我想在文本字段中输入数字时像这样格式化数字:145,636,826。我不想要逗号之间的数字,如你所说。我想在数字之间放置逗号以将它们格式化为货币。我第一次没有逗号。拆分功能不适合我的目标。
-
啊,对不起,我误会了。
-
没关系。谢谢您的回复。