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

时间:2013-12-10 05:42:35

标签: java swing awt jtextfield

我正在使用GUI进行我的第一个java程序。我需要将输入到jTextField的用户的输入更改为可用于工作的int变量。

5 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

int a = Integer.parseInt(jtextfield.getText());
// `jtextfield` will be your `JTextField` object

答案 2 :(得分:0)

    JTextField jTextField=new JTextField(); // initialize textFild
    String str=jTextField.getText(); // get text value 

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

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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());

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

相关问题