Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import javax.swing.text.PlainDocument;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.Objects;
- class MaxLengthDocument extends PlainDocument {
- private final int maxLength;
- public MaxLengthDocument(int maxLength) {
- this.maxLength = maxLength;
- }
- @Override
- public void insertString(int offset, String str, javax.swing.text.AttributeSet a) throws javax.swing.text.BadLocationException {
- if (str == null) return;
- if (getLength() + str.length() <= maxLength) {
- super.insertString(offset, str, a);
- }
- }
- }
- public class Main {
- static JTextArea textFieldWord;
- static JTextField textFieldKey;
- static JTextArea textFieldAns;
- public static String readFirst200Characters(File file) {
- StringBuilder content = new StringBuilder();
- try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
- int ch;
- int count = 0;
- while ((ch = reader.read()) != -1 && count < 200) {
- content.append((char) ch);
- count++;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return content.toString();
- }
- public static String makeCoding(String key, String word) {
- char[] arrOfKey = new char[key.length()];
- int[] arrOfIndex = new int[key.length()];
- for (int i = 0; i < arrOfKey.length; i++) {
- arrOfKey[i] = key.charAt(i);
- arrOfIndex[i] = i;
- }
- for (int i = 0; i < arrOfKey.length - 1; i++) {
- for (int j = 0; j < arrOfKey.length - 1 - i; j++) {
- if (arrOfKey[j] > arrOfKey[j + 1]) {
- char tempChar = arrOfKey[j];
- arrOfKey[j] = arrOfKey[j + 1];
- arrOfKey[j + 1] = tempChar;
- int tempIndex = arrOfIndex[j];
- arrOfIndex[j] = arrOfIndex[j + 1];
- arrOfIndex[j + 1] = tempIndex;
- }
- }
- }
- char[][] matrix = new char[word.length() / key.length() + 1][key.length()]; // двумерный массив
- int counter = 0;
- for(int i = 0; i < matrix.length; i++) {
- for(int j = 0; j < matrix[i].length; j++) {
- if(counter < word.length()) {
- matrix[i][j] = word.charAt(counter);
- counter++;
- }
- else {
- matrix[i][j] = '0';
- }
- }
- }
- String outputstring = "";
- for (int col = 0; col < matrix[0].length; col++) {
- for (int row = 0; row < matrix.length; row++) {
- if(!(matrix[row][col] == '0')) {
- outputstring += matrix[row][col];
- }
- }
- }
- return outputstring;
- }
- public static String makeCorrect(String str) {
- String correctStr = "";
- char ch;
- for(int i = 0; i < str.length(); i++) {
- ch = str.charAt(i);
- if ((ch >= 'а' && ch <= 'я') || (ch >= 'А' && ch <= 'Я') || ch == 'ё' || ch == 'Ё') {
- if((ch >= 'а') && (ch <= 'я') || ch == 'ё') {
- ch = Character.toUpperCase(ch);
- }
- correctStr += ch;
- }
- }
- return correctStr;
- }
- public static boolean isContainsLetters(String str) {
- return str.matches(".*[а-яА-ЯЁё].*");
- }
- public static boolean isCorrectInput(String key, String word) {
- boolean isOk = true;
- if ((Objects.equals(key, "")) || (!isContainsLetters(key)) || ((Objects.equals(word, "")) || (!isContainsLetters(word)))) {
- isOk = false;
- }
- else {
- if ((key.length() < 2) || (word.length() < 2)) {
- isOk = false;
- }
- }
- return isOk;
- }
- public static void main(String[] args) {
- // новое окно
- JFrame frame = new JFrame("Непесов Рустам, 351004");
- // размеры окна
- frame.setSize(1000, 1000);
- frame.setResizable(false);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- // панель для добавления компонентов
- JPanel panel = new JPanel();
- frame.add(panel);
- placeComponents(panel);
- // видимость окна
- frame.setVisible(true);
- }
- private static void placeComponents(JPanel panel) {
- panel.setLayout(null);
- // радиокнопки для выбора
- JRadioButton option1 = new JRadioButton("- «столбцовый метод» с одним ключевым словом");
- option1.setBounds(10, 20, 400, 25);
- panel.add(option1);
- JRadioButton option2 = new JRadioButton("- алгоритм Виженера, самогенерирующийся ключ");
- option2.setBounds(10, 50, 400, 25);
- panel.add(option2);
- // Группа радиокнопок
- ButtonGroup group = new ButtonGroup();
- group.add(option1);
- group.add(option2);
- // подтверждение выбора
- JButton submitButton = new JButton("Зашифровать");
- submitButton.setBounds(10, 420, 170, 25);
- panel.add(submitButton);
- JButton fileButton = new JButton("Выбрать файл");
- fileButton.setBounds(10, 450, 170, 25);
- panel.add(fileButton);
- fileButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- JFileChooser fileChooser = new JFileChooser();
- fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
- fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
- @Override
- public boolean accept(File f) {
- return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
- }
- @Override
- public String getDescription() {
- return "Текстовые файлы (*.txt)";
- }
- });
- int returnValue = fileChooser.showOpenDialog(panel);
- if (returnValue == JFileChooser.APPROVE_OPTION) {
- File selectedFile = fileChooser.getSelectedFile();
- String fileContent = readFirst200Characters(selectedFile);
- textFieldWord.setText(fileContent);
- }
- }
- });
- // Обработчик события для кнопки
- submitButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- String selectedOption = "";
- if (option1.isSelected()) {
- //шифр столбцовый
- if (!isCorrectInput(textFieldKey.getText(), textFieldWord.getText())) {
- selectedOption = "Ошибка ввода! Проверьте, чтобы были введены как минимум 2 русские буквы и поля не были пустыми";
- JOptionPane.showMessageDialog(panel, selectedOption);
- }
- else {
- String key = makeCorrect(textFieldKey.getText());
- String word = makeCorrect(textFieldWord.getText());
- String ans = makeCoding(key, word);
- textFieldAns.setText(ans);
- }
- } else if (option2.isSelected()) {
- selectedOption = "Выбрана надпись 2";
- } else {
- selectedOption = "Не выбран вид шифра!";
- }
- }
- });
- // текстова метка
- JLabel userLabel = new JLabel("Введите ключ:");
- userLabel.setBounds(10, 200, 120, 25);
- panel.add(userLabel);
- // поле для ввода текста
- textFieldKey = new JTextField(20);
- textFieldKey.setBounds(10, 225, 500, 75);
- panel.add(textFieldKey);
- textFieldKey.setDocument(new MaxLengthDocument(15));
- // текстова метка
- JLabel userLabel1 = new JLabel("Введите текст, который нужно зашифровать или выберите файл:");
- userLabel1.setBounds(10, 300, 300, 25);
- panel.add(userLabel1);
- // поле для ввода текста
- textFieldWord = new JTextArea();
- textFieldWord.setBounds(10, 325, 500, 75);
- textFieldWord.setLineWrap(true);
- textFieldWord.setWrapStyleWord(true);
- panel.add(textFieldWord);
- textFieldWord.setDocument(new MaxLengthDocument(200));
- // текстова метка
- JLabel userLabelAns = new JLabel("Зашифрованный текст:");
- userLabelAns.setBounds(10, 500, 270, 25);
- panel.add(userLabelAns);
- // поле для ввода текста
- textFieldAns = new JTextArea();
- textFieldAns.setBounds(10, 550, 500, 75);
- textFieldAns.setLineWrap(true);
- textFieldAns.setWrapStyleWord(true);
- panel.add(textFieldAns);
- textFieldAns.setEditable(false);
- textFieldAns.setDocument(new MaxLengthDocument(150));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement