2

我正在寻找一种方法来确保我的文本字段(JTextField、JFormattedTextField)在我调用 .getText() 时返回双精度或整数而不是字符串。最好的方法是什么(如果可能)?

谢谢!

坏熊猫:D

4

3 回答 3

3
  1. 注册 InputVerifiergetValue并调用方法JFormattedTextField

    public class FormattedTextFieldVerifier extends InputVerifier {
        public boolean verify(JComponent input) {
         if (input instanceof JFormattedTextField) {
             JFormattedTextField ftf = (JFormattedTextField)input;
             AbstractFormatter formatter = ftf.getFormatter();
             if (formatter != null) {
                 String text = ftf.getText();
                 try {
                      formatter.stringToValue(text);
                      return true;
                  } catch (ParseException pe) {
                      return false;
                  }
              }
          }
          return true;
      }
      public boolean shouldYieldFocus(JComponent input) {
          return verify(input);
      }
    

    }

于 2010-03-24T17:46:50.937 回答
1

我会检查文本框回调中的输入,然后简单地将框设为红色或在附近创建一条警报消息。您可以从文本框字符串中删除非数字字符。

于 2010-03-24T17:41:48.393 回答
1

使用JFormattedTextField

于 2010-03-24T17:46:03.917 回答