当前位置: 首页 > 知识库问答 >
问题:

当在另一个.java文件上按下GUI按钮时,如何执行某些任务?

蔚承天
2023-03-14
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个答案

楚昀
2023-03-14

如果我对您的代码理解正确的话:您在您的类测试中有一个静态方法用于加密和解密。您只需用如下一行话来调用此方法:

字符串encodedMessage=test.encline(sourceText,keyText,flag);

然后将该字符串写入所需的输出字段。

 类似资料:
  • 我通过一个qt designer程序创建了一个名为(first page)的简单文件,并在其中放置了一个名为(login)的按钮,我还使用相同的程序创建了另一个名为(second page)的简单文件 运行第一个文件并按下其中的按钮后,我想打开第二个文件,或者换句话说,我想将页面链接在一起。我怎么能这么做?。拜托我需要帮助。 第一个文件代码: 来自PyQt5。QtWidget导入QDialog,Q

  • 如果我按下呼叫按钮,我会得到一个错误,即出租车没有呼叫,而是转到另一个窗口。 我认为这个错误来自实时数据库。如果你有不同的意见,写下你的答案。 错误:E/AndroidRuntime:致命异常:主进程:com。实例乌兹别克斯坦,PID:8915爪哇。lang.NullPointerException:尝试调用虚拟方法“double android”。地方地方getLatitude()'位于com上

  • 我想创建一个下拉列表和一个按钮,功能是当我点击按钮,然后按钮不是可点击的意思是禁用,它是显示,首先点击下拉列表。然后按钮是启用的。我们如何使我尝试但没有发生,我没有太多的想法。所以任何机构帮助我解决这个问题。 我试过这个jquery函数我对jquery不太了解。所以谁来帮帮我。

  • 想改进这个问题吗 通过编辑此文章,添加详细信息并澄清问题。 当计数器小于3并且我等待单击按钮时,我想一直更改循环颜色。当循环是红色时,他需要按“停止”。这是程序: 非常感谢。

  • 问题内容: 我有1个活动按钮。我想将此1按钮用于多个任务。 那我该怎么办? 如果我第一次按此按钮,则更改为2按钮 如果我按了第二次,那么它将更新我的数据 但是第一次只能工作第二次不能工作 看看我的代码我尝试了什么 您可以看到我的上面的代码,我可以使用按钮执行2个任务,但是只更改两个按钮,我将更改数据并单击按钮,然后它就无法执行 问题答案: 尝试这种方式,首先在活动类文件上声明全局变量,如下所示: