-3

I have a main.java file containing the main class and multiple functions along with main function. I have imported a user defined package containing GUI.java file. The GUI has 3 text feilds and 3 buttons. I want to take the inputs from the text feilds and send them for processing to main.java file if button A or B is pressed on the GUI. I have added action listeners. How can this be achieved?

Below one is main java file:

import com.cryptogui.GUI;
import javax.swing.*;
import java.io.*;
import java.util.*;
import com.cryptogui.*;

public class Test{

//function to convert ascii values to integer values
private static int convInt(char ascii)
{
    int intVal;

    if ((ascii >= 'a') && (ascii <= 'z'))
    {
        intVal = (int) ascii;
        intVal = intVal - 97;
    }
    else
    {
        intVal = (int) ascii;
        intVal = intVal - 65;
    }

    return (intVal);
}

//function to encrypt and decrypt the letter using 'Vigenere Cipher'
private static char encOrDec(char let, char keyLet, int fl)
{
    int intLet, intKeyLet;

    intLet = convInt(let);
    intKeyLet = convInt(keyLet);

    //condition to check whether to to encrypt or decrypt if fl=0 -> Encryption; fl=1 -> Decryption
    if (fl == 0)
    {
        intLet = Math.floorMod((intLet + intKeyLet), 26);
    }
    else
    {
        intLet = Math.floorMod((intLet - intKeyLet), 26);
    }

    //converts int values 0-25 into ascii values for 'a'-'z' OR converts int values 0-25 into ascii values for 'A'-'Z'
    if ((let >= 'a') && (let <= 'z'))
    {
        let = (char) (intLet + 97);
    }
    else
    {
        let = (char) (intLet + 65);
    }

    return (let);
}

//function to break the the current line into characters and put them back together after encryption or decryption
private static String encLine(String str, String key, int flag)
{
    int i = 0, j = 0;
    char buffer;
    char keyBuf;
    String cipherText = "";

    int len = str.length();
    int len2 = key.length();

    //loop to encrypt or decrypt the line, character by character
    while (i < len)
    {
        buffer = str.charAt(i);

        //condition to check if character is a Letter
        if (((buffer >= 'A') && (buffer <= 'Z')) || ((buffer >= 'a') && (buffer <= 'z')))
        {
            //condition to make sure the key word keeps repeating itself
            if (j >= len2)
            {
                j = 0;
            }
            keyBuf = key.charAt(j);

            //character and corresponding keyword character are sent to get encrypted or decrypted
            buffer = encOrDec(buffer, keyBuf, flag);
            j++;
        }

        //cipher text is created by appending char by char
        cipherText += buffer;
        i++;
    }
    return (cipherText);
}

//function to copy file
private static void copyFile(String readFile, String writeFile)
{
    String copyLine = null;
    try
    {
        FileReader filereader = new FileReader(readFile);
        BufferedReader bufferedReader = new BufferedReader(filereader);
        FileWriter fileWriter = new FileWriter(writeFile);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        while ((copyLine = bufferedReader.readLine()) != null)
        {
            bufferedWriter.write(copyLine);
            bufferedWriter.newLine();
        }
        bufferedReader.close();
        bufferedWriter.close();
    }
    catch (FileNotFoundException ex)
    {
        System.out.println("Unable to open file '" + readFile + "'\n");
    }
    catch (IOException ex)
    {
        System.out.println("Error during copying file\n");
    }
}

public static void main(String args[])
{
    GUI mainframe = new GUI();
    mainframe.init();
    String fileRead, fileWrite, tempFile, keyWord;
    Scanner sc = new Scanner(System.in);
    File f = null;
    int flag = mainframe.flag;
    while (flag != 2)
    {
        //System.out.println("\nEnter '0' to encrypt, '1' to decrypt OR '2' to quit");
        //flag = sc.nextInt();
        //sc.nextLine();
        if (flag > 2)
        {
            flag = 2;
        }
        if ((flag == 0) || (flag == 1))
        {
            //System.out.println("Enter file path of the file to be read");
            fileRead = mainframe.sourceText;
            //System.out.println("\nEnter file path of the file to be written");
            fileWrite = mainframe.destText;
            //System.out.println("\nEnter KeyWord (keyword must not have special character,numbers,whitespaces)");
            keyWord = mainframe.keyText;

            String line = null;
            tempFile = fileWrite;

            //block to create temp file in case we to read and write in the same file
            if (fileRead.equals(fileWrite))
            {
                f = new File("tempf.txt");
                fileWrite = "tempf.txt";
            }
            try
            {
                FileReader filereader = new FileReader(fileRead);
                BufferedReader bufferedReader = new BufferedReader(filereader);
                FileWriter fileWriter = new FileWriter(fileWrite);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

                //block to read file line by line and encrypt or decrypt it and write it another file
                while ((line = bufferedReader.readLine()) != null)
                {
                    line = encLine(line, keyWord, flag);
                    bufferedWriter.write(line);
                    bufferedWriter.newLine();
                }
                bufferedReader.close();
                bufferedWriter.close();
            }
            catch (FileNotFoundException ex)
            {
                mainframe.errorDialogue(0);
                //System.out.println("Unable to open file '" + fileRead + "'\n");
            }
            catch (IOException ex)
            {
                mainframe.errorDialogue(1);
                //System.out.println("Error reading '" + fileRead + "' or writing '" + fileWrite + "' file \n");
            }

            if (fileRead.equals(tempFile))
            {
                //copies file from temp file to the original file if we have to source and dest are the same file
                copyFile(fileWrite, tempFile);

                //temp file is deleted after the process
                f.delete();
            }

            //System.out.println("File has been processed successfully. Enter one of the options from below:\n");
        }
    }
    //System.out.println("Thank for using\n");
}

}

this one is gui java file

package com.cryptogui;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GUI {
public JPanel main;
private JTextField destFeild;
private JPasswordField keywordPFeild;
private JButton encryptButton;
private JButton decryptButton;
private JLabel sourceLabel;
private JTextField sourceFeild;
private JSplitPane sourcePane;
private JSplitPane destPane;
private JLabel destLabel;
private JSplitPane keywordPane;
private JLabel keywordLabel;
private JSplitPane buttonPane;
private JButton cancelButton;
public String sourceText;
public String destText;
public String keyText;
public int flag = 10;

public GUI() {
    encryptButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            flag = 0;
            sourceText = sourceFeild.getText();
            destText = destFeild.getText();
            keyText = new String(keywordPFeild.getPassword());
            JOptionPane.showMessageDialog(null,"Encryption completed");
        }
    });
    decryptButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            flag = 1;
            sourceText = sourceFeild.getText();
            destText = destFeild.getText();
            keyText = new String(keywordPFeild.getPassword());
            JOptionPane.showMessageDialog(null,"Decryption completed");
        }
    });
    cancelButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });

}

public void init(){
    JFrame frame = new JFrame("GUI");
    frame.setContentPane(new GUI().main);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setSize(600,300);
    frame.setLocation(700,350);
    frame.setVisible(true);
}

public void errorDialogue(int x){
    if (x == 0)
    {
        JOptionPane.showMessageDialog(null,"Unable to open SOURCE FILE");
    }
    else if (x == 1)
    {
        JOptionPane.showMessageDialog(null,"Error occurred while reading SOURCE FILE or writing DEST FILE");
    }
}

}

Nithin K
  • 105
  • 3
  • 7
  • 1
    It's not possible to give you an answer on such a general question. Can you give a few more details about your methods and such? – Sven Affeld Oct 01 '18 at 09:28

1 Answers1

0

If I understand your code right: You have a static method in your class Test for encryption and decryption. You can just call this method with something like this line:

String encodedMessage = Test.encLine(sourceText, keyText, flag);

And then write that String to your desired output field.

Sven Affeld
  • 311
  • 3
  • 8
  • 1
    sourceText , destText are file paths. I have take these from the text feild in GUI and pass them on to main function when either encrypt or decrypt button is pressed – Nithin K Oct 01 '18 at 11:08
  • Okay, in that case, use a FileReader and a BufferedReader to read your file and decrypt the lines that they return. For more information on how to use FR and BR, I would recommend this: https://stackoverflow.com/questions/16104616/using-bufferedreader-to-read-text-file – Sven Affeld Oct 01 '18 at 20:01