gpt4 book ai didi

java - Swing:为什么 JFormattedTextField 在失去焦点时添加 ","

转载 作者:行者123 更新时间:2023-11-29 06:11:25 24 4
gpt4 key购买 nike

问题在标题中。

我在我的文本字段中显示一个 int 数字,但当我退出该字段时它一直在添加一个“,”...知道为什么吗?

对于代码爱好者:

onfocuslost 调用:

if(textStiffness != null){
String s1 = textStiffness.getText();
if(s1 != null){
stiffness = Float.valueOf(s1.replaceAll(",", "")).intValue();
stiffness = Math.max(0, stiffness);
}
}

然后:

if(textStiffness != null){
textStiffness.setText((""+(int)stiffness).replaceAll(",", ""));

}

我检查了字段中设置的文本及其正确的 10000,但后来它变成了 10,000,我不明白为什么

最佳答案

您仍然没有向我们展示 JFormattedTextField 正在使用的 NumberFormat,而这实际上是解决您的问题所必需的关键信息问题。我只能假设您正在使用 NumberFormat.getNumberInstance() 作为格式化程序,如果是这样,如果您检查此类的 API,您将看到该对象的 groupingUsed属性默认设置为 true。你想将它设置为 false 以摆脱你的逗号。

例如这是我的 SSCCE显示您的问题及其解决方案:

import java.awt.BorderLayout;
import java.text.NumberFormat;

import javax.swing.*;

public class FormattedFieldFun {
private static void createAndShowUI() {
NumberFormat numberFormatGuFalse = NumberFormat.getNumberInstance();
numberFormatGuFalse.setGroupingUsed(false); // ***** HERE *****
JFormattedTextField jftFieldGuFalse =
new JFormattedTextField(numberFormatGuFalse);

NumberFormat numberFormatGuTrue = NumberFormat.getNumberInstance();
// numberFormatGuFalse.setGroupingUsed(true); // not necessary as is default
JFormattedTextField jftFieldGuTrue =
new JFormattedTextField(numberFormatGuTrue);

JPanel panel = new JPanel(new BorderLayout());
panel.add(jftFieldGuFalse, BorderLayout.NORTH);
panel.add(jftFieldGuTrue, BorderLayout.SOUTH);

JFrame frame = new JFrame("FormattedFieldFun");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

关于java - Swing:为什么 JFormattedTextField 在失去焦点时添加 ",",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6701217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com