【问题标题】:How to retrieve string value call from existing specific JButton variable in java?如何从java中现有的特定JButton变量中检索字符串值调用?
【发布时间】:2021-11-07 15:55:42
【问题描述】:
    private void jButton_1ActionPerformed(java.awt.event.ActionEvent evt) {                                                

    String text = "";

    texto = RandomStringUtils.randomAlphanumeric(12);
    System.out.println(text);
    JOptionPane.showMessageDialog(null, text);

    }

我需要检索变量字符串text

    private void jButton_2ActionPerformed(java.awt.event.ActionEvent evt) {                                                 

    String code, text = "";

    text = *??????*;   /*<-----This variable I need to retrieve the previous generated button*/
    code = txt_code.getText().trim();

    if (code.equals("")) {
        jLabel_codeerror.setText("This information is required.");
    } else {
        if (code.equals(text)) {
            jLabel_codeerror.setText("Equal code.");
        } else {
            jLabel_codeerror.setText("The confirmation has failed, please try again.");

               }
        }
    }

我不知道如何从其他按钮中提取变量,我需要,因为每个按钮都有不同的变量,以后我必须在最后一个按钮中收集它们来更新它

非常感谢

【问题讨论】:

  • 变量text,在方法@​​987654325@中是一个局部变量。它不存在于该方法之外。因此,您无法从其他方法访问它。 @Babasile 在他的answer 中建议您将text 设为类成员变量,让您可以从任何方法访问它。
  • 我觉得有更好的方法来做你想做的事。我了解您想要显示一些随机文本并让用户输入完全相同的文本,以执行某种验证用户是人类用户而不是某种机器人的方式。对吗?

标签: java string swing jbutton actionevent


【解决方案1】:

我通过在我的公共类中创建变量来解决它。

private String code = ""; 

所以我可以得到生成的代码并保存以供以后比较,虽然我害怕任何人都可以看到生成的代码。因为我会用它来加密下面的信息。

【讨论】:

    【解决方案2】:

    您可以使用 getter/setter 来检索您的值。

    private String yourText;
    
    public void setYourText(String yourText) {
       this.yourText = yourText;
    }
    
    public String getYourText() {
       return this.yourText ;
    }
    
    private void jButton_1ActionPerformed(java.awt.event.ActionEvent evt) {                                                
    
    
    String text = "";
    
      texto = RandomStringUtils.randomAlphanumeric(12);
      System.out.println(text);
      JOptionPane.showMessageDialog(null, text);
      setYourText(text);
    
    }
    
    private void jButton_2ActionPerformed(java.awt.event.ActionEvent evt) {                                                 
    
       String code, text = "";
    
       text = getYourText();
    
       code = txt_code.getText().trim();
    
       if (code.equals("")) {
          jLabel_codeerror.setText("This information is required.");
       } else {
          if (code.equals(text)) {
            jLabel_codeerror.setText("Equal code.");
          } else {
             jLabel_codeerror.setText("The confirmation has failed, please try again.");
    
          }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 2017-09-16
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 2021-09-04
      相关资源
      最近更新 更多