【问题标题】:Get text from textfield从文本字段中获取文本
【发布时间】:2013-10-01 14:51:16
【问题描述】:

我正在制作一个 GUI 程序。在我的第一个程序中,我有以下代码:

double num1;
num1 = Double.parseDouble(guess.getText());

我相信这段代码从文本字段中获取值并将其转换为双精度值。

如何获取值并将其转换为 String 或 Char?

【问题讨论】:

    标签: java swing textfield jtextfield


    【解决方案1】:

    由于getText() 已经返回String,将其值存储为String 很简单。

    为了解析double,您已经完成了,只需注意NumberFormatException,以防输入无效。

    要将其值存储为char,这取决于您的要求。你想要第一个角色吗?您是否要求字符串只有一个字符?任何字符都有效吗?以此类推。

    // Storing the value as a String.
    String value = guess.getText();
    
    // Storing the value as a double.
    double doubleValue;
    try {
        doubleValue = Double.parseDouble(value);
    } catch (NumberFormatException e) {
        // Invalid double String.
    }
    
    // Storing the value as a char.
    char firstChar = value.length() > 0 ? value.charAt(0) : (char) 0;
    
    // Require the String to have exactly one character.
    if (value.length() != 1) {
        // Error state.
    }
    char charValue = value.charAt(0);
    

    【讨论】:

      【解决方案2】:

      使用 String.valueOf() 代替 Double.parseDouble() 这将帮助您将 double 转换为字符串值

      【讨论】:

        【解决方案3】:

        getText() 已经将文本作为字符串返回。 顺便说一句,由于解析错误,请注意异常。但你在正确的轨道上。 :)

        【讨论】:

          【解决方案4】:

          getText()方法返回一个字符串。当您使用.parseDouble 时,您真正要做的是将用户输入的字符串转换为双精度因此在字符串的情况下您不必使用 .parse 方法,因为调用的值已经是一个字符串。如果是一个角色,你必须使用这样的东西:

          String text = jTextField1.getText();
          if (text.length() > 1 && !text.contains(" ") && !text.contains(",")) {
              //make sure that its length is not over 1, and that it has no spaces and no commas 
              char ch = text;
          } else {
              //if a space or comma was found no matter how big the text it will execute the else.. 
              System.out.println("this is not allowed");
              jTextField1.setText("");
          }
          

          【讨论】:

          • 您对char 案例的逻辑似乎有点混乱。你想达到什么目的?
          • @afsantos 类似这样的东西:char abc = String;
          【解决方案5】:

          getText() 函数已经从Textfield 中获取String 值。

          例如:

          String var = guess.getText();
          

          这里,var 存储从Textfield 接收到的String 值。

          【讨论】:

            猜你喜欢
            • 2021-08-17
            • 2018-10-25
            • 1970-01-01
            • 2021-10-06
            • 2017-12-01
            • 2012-07-21
            • 1970-01-01
            相关资源
            最近更新 更多