繁体   English   中英

如何将用户输入字符串(jtextfield)更改为int变量?

[英]how do I change a user input string (jtextfield) into an int variable?

我正在用GUI做我的第一个Java程序。 我需要将输入到jTextField中的用户的输入更改为我可以用于工作的int变量。

获取文本并使用Integer.parseInt(此处为您的String);

int a = Integer.parseInt(jtextfield.getText());
// `jtextfield` will be your `JTextField` object
    JTextField jTextField=new JTextField(); // initialize textFild
    String str=jTextField.getText(); // get text value 

现在,您可以将其转换为int值。

    int val=Integer.parseInt(jTextField.getText());

jtextfield.gettext()将返回输入的String ..我们可以将此字符串解析为整数

integer.parseInt(txtfield.getText());

但是如果我们在文本字段中键入数字0-9以外的值,则会显示java.lang.NumberFormatException

只能将数字解析为整数

int num=Integer.parseInt("2")// is correct

int num=Integer.parseInt("two")//this will give numberformat exception
int result = Integer.parseInt(jTextField.getText());

并申请

class MyIntFilter extends DocumentFilter {
   @Override
   public void insertString(FilterBypass fb, int offset, String string,
         AttributeSet attr) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.insert(offset, string);

      if (test(sb.toString())) {
         super.insertString(fb, offset, string, attr);
      } else {
         // warn the user and don't allow the insert
      }
   }

   private boolean test(String text) {
      try {
         Integer.parseInt(text);
         return true;
      } catch (NumberFormatException e) {
         return false;
      }
   }

   @Override
   public void replace(FilterBypass fb, int offset, int length, String text,
         AttributeSet attrs) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.replace(offset, offset + length, text);

      if (test(sb.toString())) {
         super.replace(fb, offset, length, text, attrs);
      } else {
         // warn the user and don't allow the insert
      }

   }

   @Override
   public void remove(FilterBypass fb, int offset, int length)
         throws BadLocationException {
      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.delete(offset, offset + length);

      if (test(sb.toString())) {
         super.remove(fb, offset, length);
      } else {
         // warn the user and don't allow the insert
      }

   }
}

(该类从Link复制)

PlainDocument doc = (PlainDocument) jTextField.getDocument();
doc.setDocumentFilter(new MyIntFilter());

这样,您可以将输入限制为数字,并通过解析将字符串转换为整数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM