문제

I have developed small program in swing which will convert the message to the encrypted form. I don't have any idea about this, why this is not working.

public class Encrypt extends javax.swing.JFrame {
String OriginalMsg,EncryptedMsg;

public Encrypt() {
    initComponents();
    OriginalMsg = jTextArea1.getText().toString();
    EncryptedMsg = jTextArea2.getText().toString();

}
public void action(int a){
    if(a == 0){
        StringBuffer sb = new StringBuffer(OriginalMsg);
        for(int i = 0; i < sb.length(); i++){
            int temp = 0;
            temp = (int)sb.charAt(i);
            temp = temp * 11;
            sb.setCharAt(i, (char)temp);
            EncryptedMsg = sb.toString();
        }
        jTextArea2.setText(EncryptedMsg);
   }
    else if(a == 1){
        jTextArea1.setText("");
        jTextArea2.setText("");

    }
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
 action(0);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){
 action(1);
}
도움이 되었습니까?

해결책

Your constructor is getting the values of the text areas at a point where they will always be empty.

At the very least you need to make these changes:

public Encrypt() {
    initComponents();
}

public void action(int a){
    if(a == 0){
        OriginalMsg = jTextArea1.getText().toString();
        EncryptedMsg = jTextArea2.getText().toString();
        StringBuffer sb = new StringBuffer(OriginalMsg);
        for(int i = 0; i < sb.length(); i++){
            int temp = 0;
            temp = (int)sb.charAt(i);
            temp = temp * 11;
            sb.setCharAt(i, (char)temp);
            EncryptedMsg = sb.toString();
        }
        jTextArea2.setText(EncryptedMsg);
   }
    else if(a == 1){
        jTextArea1.setText("");
        jTextArea2.setText("");

    }
}

Here is a useful post about String immutability:

Immutability of Strings in Java

다른 팁

If the program is intended to encrypt whatever the user enters in jTextArea1 (and not some value that may be set up in initComponents()) you will need to set the value of your OriginalMsg field after the user has entered the text.

Set it at the start of your action method.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top