当在不同的.java文件上按下GUI按钮时,如何执行某些任务?

时间:2018-10-01 09:21:41

标签: java user-interface

我有一个main.java文件,其中包含main类和多个函数以及main函数。 我已经导入了一个包含GUI.java文件的用户定义包。 GUI具有3个文本字段和3个按钮。 如果要在GUI上按下按钮A或B,我想从文本字段获取输入并将其发送到main.java文件进行处理。我添加了动作监听器。如何实现?

下面是主要的Java文件:

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

}

这是GUI Java文件

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

}

1 个答案:

答案 0 :(得分:0)

如果我对您的代码理解正确:您的类Test中有一个静态方法用于加密和解密。您可以使用以下代码行调用此方法:

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

然后将String写入所需的输出字段。