Search code examples
javastringswingjbuttonactionevent

How to retrieve string value call from existing specific JButton variable in java?


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

    String text = "";

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

    }

I need to retrieve the variable String 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.");

               }
        }
    }

I do not know how to extract the variables from the other buttons, and I need since each button has different variables that later I have to gather them in the last button to update it

Thank you so much


Solution

  • You could use getter/setter to retrieve your value.

    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.");
    
          }
        }
    }