设置实时小数格式为JOptionPane.showInputDialog

问题描述 投票:0回答:1

我有一个具有十进制格式的

JFormattedTextField
,如果该值低于或等于 0,则会显示
showInputDialog
来更新它。

如何为

showInputDialog
设置“实时”十进制格式化程序?

// Format
NumberFormat format = DecimalFormat.getInstance();
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
format.setRoundingMode(RoundingMode.HALF_UP);


// Text field
JFormattedTextField textField = new JFormattedTextField();


// Validation
String regex = "[.,]";
String valueString = textField.getText().split(",")[0].replaceAll(regex, "");
int value = (int) Double.parseDouble(valueString);

while(value <= 0) {
    value = Integer.valueOf(JOptionPane.showInputDialog(parentComponent, "The value must be greater than 0", "Warning", JOptionPane.WARNING_MESSAGE));
}

我不知道该怎么做。

java swing integer dialog joptionpane
1个回答
0
投票

NumberFormatter(或 MaskFormatter)可能就是您正在寻找的。

NumberFormat format = DecimalFormat.getInstance();
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
format.setRoundingMode(RoundingMode.HALF_UP);

NumberFormatter formatter = new NumberFormatter(format); //also check MaskFormatter 
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
formatter.setAllowsInvalid(false);

// value is be committed on each keystroke instead of focus lost
    formatter.setCommitsOnValidEdit(true);
    
 JFormattedTextField textField  = new JFormattedTextField(formatter);
© www.soinside.com 2019 - 2024. All rights reserved.