Я делаю простое приложение с графическим интерфейсом для генерации хеша текстового файла с использованием Java Swing.
Я также использовал очень простой алгоритм хеширования.
Код HashGui
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
@SuppressWarnings("serial")
public class HashGui extends JPanel
{
private JTextArea textOutput;
private JLabel hashDisplay;
String textFileInfo = fileOpener();//Converts the loaded file into a
//string to be displayedon the JTextArea.
//String pathInfo = fileOpener();
public HashGui()
{
gui();//this is called as a method
}
/**The method -
public void gui()
is the main area where all the GUI codes are implemented. All the
components,
including JFrame, JPanels, menubars, and buttons are added here.*/
public void gui()
{
JFrame mainFrame = new JFrame("Encryption-Decryption
application");
// Creates a constructor for JFrame.
JMenuBar bar = new JMenuBar();
mainFrame.setJMenuBar(bar);
JMenu file = new JMenu("File");
bar.add(file);
JMenuItem load = new JMenuItem("Load");
file.add(load);
load.addActionListener(new LoadClick());
JMenuItem exit = new JMenuItem("Exit");
file.add(exit);
exit.addActionListener(new ExitClick());
JMenu help = new JMenu("More");
bar.add(help);
JMenuItem about = new JMenuItem("About");
help.add(about);
about.addActionListener(new AboutClick());
//Jmenu end
JPanel jpOne = new JPanel();
//*****************************************************
//JTextArea output for loaded text output
textOutput = new JTextArea(40, 20);
textOutput.setSize(250, 20);
textOutput.setLineWrap(true);
textOutput.setText(textFileInfo);
JScrollPane pane = new JScrollPane(textOutput);
//JScrollPane adds a scrollbar to the top and bottom of the
JTextArea.
//jpOne end
JPanel jpTwo = new JPanel();
//******************
JButton hash = new JButton("Hash");
jpTwo.add(hash);
hash.addActionListener(new HashClick());
hashDisplay = new JLabel("hash");
//jpTwo end
/**mainFrame.add() adds the JPanels to the JFrame. And,
JPanel.add() implements the various
components like, buttons, labels and text area to the
JPanels.*/
mainFrame.add(jpOne);
mainFrame.add(jpTwo);
/**
GridLayout: setting side by side GridLayout
mainFrame.setLayout(new GridLayout(vetical, horizontal);
creates a grid where all the JPanels or other
components can be set in a specific grid.*/
//
mainFrame.setLayout(new GridLayout(5, 1));
//******************************8*******************************
//Adding components to JPanel
jpOne.add(pane);
jpTwo.add(hashDisplay);
//setting JPanel size
jpOne.setSize(800, 250);
jpTwo.setSize(800, 250);
//***************************************************************
//setting parameters for JFrame
mainFrame.setVisible(true); //the frame needs to be made visible.
mainFrame.setSize(800, 600); //Sets frame size to 800px by 600px.
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Closes
//application on pressing the 'X' button on the top right corner.
}// void gui end
//***************************************************************
/*The public String fileOpener() section has various codes in order to
open a file choose
menu, and load a file.*/
public String fileOpener()
{
//fileLoader start
JFileChooser chooser = new JFileChooser();
int status = chooser.showOpenDialog(null);/*Opens
. dialogbox to
. open files.*/
try
{
if (status != JFileChooser.APPROVE_OPTION)
{
return null;
// Error handling
}
else
{
File file = chooser.getSelectedFile();
System.out.println(file.getAbsolutePath());
//Displays text to JTextArea textOutput after file is
//loaded.
@SuppressWarnings("resource")
BufferedReader bf= new BufferedReader(new
FileReader(file));
String line;
String fullText="";
System.out.println("I am here");
while((line=bf.readLine())!=null)
{
fullText=fullText+line;
System.out.println(fullText);
}
return fullText;
}//else end
} catch (Exception e)
{
System.out.println(e);
return "Error occurs while loading in the" + "\n" +
"beginning." + "\n" + "Load from file menu";
}//try catch end
}//filechooser end
//Maybe make FileChooser for listing file in directory in a
//JTextArea
/**This public static void main calls the class
as a constructor with the code -
- new HashGui(); */
public static void main(String[] args)
{
new HashGui();
}// main end
/**An ActionListener adds events to the GUI objects.
This includes the menubar, and the three buttons for encryption,
decryption, and
hashing.*/
/**The class ExitClick is an action listener for the exit menu button.
Once clicked, it
it completely terminats the application.*/
class ExitClick implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);//System.exit is used to procedurally terminate
the spplication.
}//ExitClick listener end
}// ExitClick end
/**The class AboutClick opens a dialogbox displaying the Information
of the application.
It is a menu item.*/
class AboutClick implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "This program generates a
hashcode for a generated text, filename, metadata, and
filepath.", "About",
JOptionPane.INFORMATION_MESSAGE);
//Opens a dialogbox to show Info about the application.
}//AboutClick listener end
}// AboutClick end
/**The class LoadClick will load a text file into the JTextArea --
textOutput. It is located
under the File menu.*/
class LoadClick implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String textFileInfo = fileOpener();
textOutput.setText(textFileInfo);//Displays the content of the
//text file on the JTextArea
}//loadClick listener end
}// LoadClick end
//hash for loaded text
class HashClick implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String textTobeHashed=textOutput.getText();//fetches plain
//text from TextArea to be hashed
String hashedText=MainHash.hasCod(textTobeHashed);//generates
//hash
hashDisplay.setText(hashedText);//displays hash on the Label.
}//HashClick listener end
}//HashClick end
}// class end
Код для алгоритма хеширования MainHash.java
public class MainHash
{
//is called when hash of the string has to be generated, always send
//non encrypted text here
public static String hasCod(String value)
{
char[] charArray=value.toCharArray();
char[] resultantArray=new char[charArray.length];
for(int i=0;i<charArray.length;i++)
{
resultantArray[i]=(char)(((int)charArray[i]/7)*13+19);
}//for end
return new String(resultantArray);
}//hash end
}//class end
После того, как я загружаю текстовый файл и нажимаю кнопку хэша, значение хэша не отображается в шестнадцатеричном или числовом формате. когда я пытался использовать
строковый формат в HashClick ActionListener, ничего не будет отображаться.
Итак, прошу вас помочь мне найти решение.
Спасибо.