Java 如何在文本字段中设置数学表达式的格式?
我正在创建一个计算器软件。在我键入的文本字段中,整个表达式显示为一个字符串(我希望保持这种方式)。下面是一个演示:Java 如何在文本字段中设置数学表达式的格式?,java,swing,calculator,number-formatting,jformattedtextfield,Java,Swing,Calculator,Number Formatting,Jformattedtextfield,我正在创建一个计算器软件。在我键入的文本字段中,整个表达式显示为一个字符串(我希望保持这种方式)。下面是一个演示: 我希望它的格式如下: 数字-##################(将它们分组为3位数组,仅在需要时显示分数,最多只能显示6位数。) 运算符和括号-####×(###-######)/####(不应导致任何格式错误或问题。我不在乎数字和运算符/括号之间是否有空格。) 以下是正确格式的上述示例: 1.000×(5-3)/2 我还希望它在我键入时自动更新格式 迄今为止,我尝试
我希望它的格式如下:
- 数字-##################(将它们分组为3位数组,仅在需要时显示分数,最多只能显示6位数。)
- 运算符和括号-####×(###-######)/####(不应导致任何格式错误或问题。我不在乎数字和运算符/括号之间是否有空格。)
迄今为止,我尝试将
JFormattedTextField
与MaskFormatters
和NumberFormat
一起使用,但它们都没有达到我想要的效果(如上所述)
数字格式版本
public class Frame {
private NumberFormat numberFormat = NumberFormat.getInstance();
private JFormattedTextField textField = new JFormattedTextField(numberFormat);
}
MaskFormatter版本
public class Frame {
private MaskFormatter maskFormat;
private JFormattedTextField textField;
public Frame() {
try {
maskFormat = new MaskFormatter("###.###.###,######");
} catch (ParseException e) {
e.printStackTrace();
}
textField = new JFormattedTextField(maskFormat);
}
}
我设法使用
DecimalFormat
格式化结果,但我不希望只格式化结果
格式化结果
DecimalFormat resultFormat = new DecimalFormat("###,###,###.######");
String result = resultFormat.format(Parser.evaluate(expression));
textField.setText(result);
当我计算5/3时,结果是:
正如我所想
很抱歉发布了如此详细和冗长的帖子,非常感谢您的帮助试试这个
DecimalFormat resultFormat = new DecimalFormat("###,###,###.######");
Pattern numberPattern = Pattern.compile("\\d+(\\.\\d+)?");
String s = "1000×(5-3)/2";
Matcher m = numberPattern.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
double value = Double.parseDouble(m.group());
String formatted = resultFormat.format(value);
m.appendReplacement(sb, formatted);
}
m.appendTail(sb);
System.out.println(sb);
// -> 1,000×(5-3)/2
“正如我所希望的”“优秀给自己打高分,然后我会使用JTextField并在字段中添加DocumentFilter(甚至扩展PlainDocument).获取文本,检测数字,设置格式,然后传递给Document@gpasch这不是我问题的答案,它按照我想要的方式格式化结果,但当我键入表达式时,它不起作用。为什么这么消极?@MarkoKitonjics你可以使用一个键盘侦听器,在每个按键上格式化数字,这是你需要的还是…?你需要我有一个复杂的问题,这个问题不是很容易解决的。我从一个
DocumentFilter