Search code examples
javaswingencryptionstringbuffer

simple encryption using ASCII values


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

Solution

  • 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