Java Swing:JFormattedTextField为什么要添加“&引用;关于失去焦点
问题在标题中 我在文本字段中显示一个整数,但当我退出该字段时,它会不断添加一个“,”。。。你知道为什么吗 对于代码爱好者: onfocuslost调用:Java Swing:JFormattedTextField为什么要添加“&引用;关于失去焦点,java,swing,jformattedtextfield,Java,Swing,Jformattedtextfield,问题在标题中 我在文本字段中显示一个整数,但当我退出该字段时,它会不断添加一个“,”。。。你知道为什么吗 对于代码爱好者: onfocuslost调用: if(textStiffness != null){ String s1 = textStiffness.getText(); if(s1 != null){ stiffness = Float.valueOf(s1.replaceAll(",", "")).int
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,但后来它变为10000,我不明白为什么阅读时,我发现了一些观察结果:
注意:某些格式化程序可能会不断更新该值,从而使失去焦点变得毫无意义,因为该值始终与文本指定的值相同
请注意,尽管JFormattedTextField类继承了JTextField类的setText方法,但通常不会对格式化文本字段调用setText方法。如果这样做,则字段的显示会相应更改,但值不会更新(除非字段的格式化程序不断更新)
还有setFocusLostBehavior(int)
:
指定字段失去焦点的结果。可能的值在JFormattedTextField中定义为COMMIT_或_REVERT(默认值)、COMMIT(如果有效,则提交,否则保持不变)、PERSIST(不执行任何操作)和REVERT(更改文本以反映值)
您仍然没有向我们显示
JFormattedTextField
使用的NumberFormat
,而这实际上是解决问题所需的关键信息。我只能假设您正在为格式化程序使用NumberFormat.getNumberInstance()
,如果是这样,如果您检查该类的API,您将看到对于该对象,groupingUsed属性默认设置为true。您希望将其设置为false以除去逗号
例如,这是我的,显示了您的问题及其解决方案:
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();
}
});
}
}
你有一个代码片段吗?你能把焦点丢失操作/方法的代码发布到哪里吗?不,谁需要代码。我们应该很好地猜测他的代码在做什么,因为我们有超能力+1:)我喜欢“代码爱好者”。好的一个,保持一个好心情是很好的……”对于代码爱好者来说:“,这对我们仍然没有帮助。我肯定你以前被要求发布一个SSCCE。这是关于数字实例的,如果没有更改区域设置+1.