Advertisement
dxvmxnd

Untitled

Feb 20th, 2025
9
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.86 KB | None | 0 0
  1. import javax.swing.*;
  2. import javax.swing.text.PlainDocument;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.io.BufferedReader;
  6. import java.io.File;
  7. import java.io.FileReader;
  8. import java.io.IOException;
  9. import java.util.Objects;
  10.  
  11. class MaxLengthDocument extends PlainDocument {
  12. private final int maxLength;
  13.  
  14. public MaxLengthDocument(int maxLength) {
  15. this.maxLength = maxLength;
  16. }
  17.  
  18. @Override
  19. public void insertString(int offset, String str, javax.swing.text.AttributeSet a) throws javax.swing.text.BadLocationException {
  20. if (str == null) return;
  21. if (getLength() + str.length() <= maxLength) {
  22. super.insertString(offset, str, a);
  23. }
  24. }
  25. }
  26.  
  27. public class Main {
  28. static JTextArea textFieldWord;
  29. static JTextField textFieldKey;
  30. static JTextArea textFieldAns;
  31.  
  32. public static String readFirst200Characters(File file) {
  33. StringBuilder content = new StringBuilder();
  34. try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
  35. int ch;
  36. int count = 0;
  37. while ((ch = reader.read()) != -1 && count < 200) {
  38. content.append((char) ch);
  39. count++;
  40. }
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. return content.toString();
  45. }
  46.  
  47. public static String makeCoding(String key, String word) {
  48. char[] arrOfKey = new char[key.length()];
  49. int[] arrOfIndex = new int[key.length()];
  50.  
  51. for (int i = 0; i < arrOfKey.length; i++) {
  52. arrOfKey[i] = key.charAt(i);
  53. arrOfIndex[i] = i;
  54. }
  55.  
  56. for (int i = 0; i < arrOfKey.length - 1; i++) {
  57. for (int j = 0; j < arrOfKey.length - 1 - i; j++) {
  58. if (arrOfKey[j] > arrOfKey[j + 1]) {
  59.  
  60. char tempChar = arrOfKey[j];
  61. arrOfKey[j] = arrOfKey[j + 1];
  62. arrOfKey[j + 1] = tempChar;
  63.  
  64. int tempIndex = arrOfIndex[j];
  65. arrOfIndex[j] = arrOfIndex[j + 1];
  66. arrOfIndex[j + 1] = tempIndex;
  67. }
  68. }
  69. }
  70.  
  71. char[][] matrix = new char[word.length() / key.length() + 1][key.length()]; // двумерный массив
  72. int counter = 0;
  73.  
  74. for(int i = 0; i < matrix.length; i++) {
  75. for(int j = 0; j < matrix[i].length; j++) {
  76. if(counter < word.length()) {
  77. matrix[i][j] = word.charAt(counter);
  78. counter++;
  79. }
  80. else {
  81. matrix[i][j] = '0';
  82. }
  83. }
  84. }
  85.  
  86.  
  87. String outputstring = "";
  88. for (int col = 0; col < matrix[0].length; col++) {
  89. for (int row = 0; row < matrix.length; row++) {
  90. if(!(matrix[row][col] == '0')) {
  91. outputstring += matrix[row][col];
  92. }
  93. }
  94. }
  95.  
  96. return outputstring;
  97. }
  98.  
  99. public static String makeCorrect(String str) {
  100. String correctStr = "";
  101. char ch;
  102.  
  103. for(int i = 0; i < str.length(); i++) {
  104. ch = str.charAt(i);
  105. if ((ch >= 'а' && ch <= 'я') || (ch >= 'А' && ch <= 'Я') || ch == 'ё' || ch == 'Ё') {
  106. if((ch >= 'а') && (ch <= 'я') || ch == 'ё') {
  107. ch = Character.toUpperCase(ch);
  108. }
  109. correctStr += ch;
  110. }
  111. }
  112.  
  113. return correctStr;
  114. }
  115.  
  116. public static boolean isContainsLetters(String str) {
  117. return str.matches(".*[а-яА-ЯЁё].*");
  118. }
  119.  
  120. public static boolean isCorrectInput(String key, String word) {
  121. boolean isOk = true;
  122.  
  123. if ((Objects.equals(key, "")) || (!isContainsLetters(key)) || ((Objects.equals(word, "")) || (!isContainsLetters(word)))) {
  124. isOk = false;
  125. }
  126. else {
  127. if ((key.length() < 2) || (word.length() < 2)) {
  128. isOk = false;
  129. }
  130. }
  131.  
  132. return isOk;
  133.  
  134. }
  135.  
  136. public static void main(String[] args) {
  137. // новое окно
  138. JFrame frame = new JFrame("Непесов Рустам, 351004");
  139.  
  140. // размеры окна
  141. frame.setSize(1000, 1000);
  142. frame.setResizable(false);
  143. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  144.  
  145. // панель для добавления компонентов
  146. JPanel panel = new JPanel();
  147. frame.add(panel);
  148. placeComponents(panel);
  149.  
  150. // видимость окна
  151. frame.setVisible(true);
  152. }
  153.  
  154. private static void placeComponents(JPanel panel) {
  155. panel.setLayout(null);
  156.  
  157. // радиокнопки для выбора
  158. JRadioButton option1 = new JRadioButton("- «столбцовый метод» с одним ключевым словом");
  159. option1.setBounds(10, 20, 400, 25);
  160. panel.add(option1);
  161.  
  162. JRadioButton option2 = new JRadioButton("- алгоритм Виженера, самогенерирующийся ключ");
  163. option2.setBounds(10, 50, 400, 25);
  164. panel.add(option2);
  165.  
  166. // Группа радиокнопок
  167. ButtonGroup group = new ButtonGroup();
  168. group.add(option1);
  169. group.add(option2);
  170.  
  171. // подтверждение выбора
  172. JButton submitButton = new JButton("Зашифровать");
  173. submitButton.setBounds(10, 420, 170, 25);
  174. panel.add(submitButton);
  175.  
  176. JButton fileButton = new JButton("Выбрать файл");
  177. fileButton.setBounds(10, 450, 170, 25);
  178. panel.add(fileButton);
  179.  
  180. fileButton.addActionListener(new ActionListener() {
  181. @Override
  182. public void actionPerformed(ActionEvent e) {
  183. JFileChooser fileChooser = new JFileChooser();
  184. fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  185. fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
  186. @Override
  187. public boolean accept(File f) {
  188. return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
  189. }
  190.  
  191. @Override
  192. public String getDescription() {
  193. return "Текстовые файлы (*.txt)";
  194. }
  195. });
  196.  
  197. int returnValue = fileChooser.showOpenDialog(panel);
  198. if (returnValue == JFileChooser.APPROVE_OPTION) {
  199. File selectedFile = fileChooser.getSelectedFile();
  200. String fileContent = readFirst200Characters(selectedFile);
  201. textFieldWord.setText(fileContent);
  202. }
  203. }
  204. });
  205.  
  206.  
  207. // Обработчик события для кнопки
  208. submitButton.addActionListener(new ActionListener() {
  209. @Override
  210. public void actionPerformed(ActionEvent e) {
  211. String selectedOption = "";
  212. if (option1.isSelected()) {
  213. //шифр столбцовый
  214. if (!isCorrectInput(textFieldKey.getText(), textFieldWord.getText())) {
  215. selectedOption = "Ошибка ввода! Проверьте, чтобы были введены как минимум 2 русские буквы и поля не были пустыми";
  216. JOptionPane.showMessageDialog(panel, selectedOption);
  217. }
  218. else {
  219. String key = makeCorrect(textFieldKey.getText());
  220. String word = makeCorrect(textFieldWord.getText());
  221. String ans = makeCoding(key, word);
  222. textFieldAns.setText(ans);
  223.  
  224. }
  225. } else if (option2.isSelected()) {
  226. selectedOption = "Выбрана надпись 2";
  227. } else {
  228. selectedOption = "Не выбран вид шифра!";
  229. }
  230. }
  231. });
  232.  
  233. // текстова метка
  234. JLabel userLabel = new JLabel("Введите ключ:");
  235. userLabel.setBounds(10, 200, 120, 25);
  236. panel.add(userLabel);
  237.  
  238. // поле для ввода текста
  239. textFieldKey = new JTextField(20);
  240. textFieldKey.setBounds(10, 225, 500, 75);
  241. panel.add(textFieldKey);
  242. textFieldKey.setDocument(new MaxLengthDocument(15));
  243.  
  244.  
  245. // текстова метка
  246. JLabel userLabel1 = new JLabel("Введите текст, который нужно зашифровать или выберите файл:");
  247. userLabel1.setBounds(10, 300, 300, 25);
  248. panel.add(userLabel1);
  249.  
  250. // поле для ввода текста
  251. textFieldWord = new JTextArea();
  252. textFieldWord.setBounds(10, 325, 500, 75);
  253. textFieldWord.setLineWrap(true);
  254. textFieldWord.setWrapStyleWord(true);
  255. panel.add(textFieldWord);
  256. textFieldWord.setDocument(new MaxLengthDocument(200));
  257.  
  258. // текстова метка
  259. JLabel userLabelAns = new JLabel("Зашифрованный текст:");
  260. userLabelAns.setBounds(10, 500, 270, 25);
  261. panel.add(userLabelAns);
  262.  
  263. // поле для ввода текста
  264. textFieldAns = new JTextArea();
  265. textFieldAns.setBounds(10, 550, 500, 75);
  266. textFieldAns.setLineWrap(true);
  267. textFieldAns.setWrapStyleWord(true);
  268. panel.add(textFieldAns);
  269. textFieldAns.setEditable(false);
  270. textFieldAns.setDocument(new MaxLengthDocument(150));
  271. }
  272.  
  273. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement