Пошаговое выполнение цикла при нажатии на кнопку - Java

Узнай цену своей работы

Формулировка задачи:

Здравствуйте! Не знаю, как реализовать пошаговое выполнение цикла при нажатии на кнопку. Среда Eclipse Neon.2 По задаче, как видите, имеется гномья сортировка массива. Изначально был консольный вариант, необходимо переделать под GUI с оговоренными выше условиями. Просьба не ругаться на лишние импорты, т.к WindowBuilder стоит, но не отображается в списке компонентов ===> приходится все элементы прописывать ручками.
Листинг программы
  1. package dlab6_1;
  2. import java.awt.EventQueue;
  3. import java.awt.FlowLayout;
  4. import javax.swing.JFrame;
  5. import javax.swing.JLabel;
  6. import javax.swing.JOptionPane;
  7. import javax.swing.JPanel;
  8. import java.awt.BorderLayout;
  9. import java.awt.Color;
  10. import java.awt.Dimension;
  11. import java.awt.Font;
  12. import java.awt.Frame;
  13. import java.awt.TextArea;
  14. import java.awt.Toolkit;
  15. import javax.swing.SwingConstants;
  16. import javax.swing.JRadioButton;
  17. import javax.swing.ButtonGroup;
  18. import javax.swing.JButton;
  19. import javax.swing.JTextField;
  20. import java.awt.event.ActionListener;
  21. import java.awt.event.WindowEvent;
  22. import java.awt.event.WindowListener;
  23. import java.awt.event.WindowStateListener;
  24. import java.awt.event.ActionEvent;
  25. import java.io.BufferedReader;
  26. import java.io.FileWriter;
  27. import java.io.IOException;
  28. import java.io.InputStreamReader;
  29. import java.io.Writer;
  30. import java.nio.charset.Charset;
  31. import java.nio.file.Files;
  32. import java.nio.file.Paths;
  33. import java.util.ArrayList;
  34. import java.util.List;
  35. import java.util.TimerTask;
  36. import java.util.concurrent.Executors;
  37. import java.util.concurrent.ScheduledExecutorService;
  38. import java.util.concurrent.TimeUnit;
  39. import java.util.logging.Level;
  40. import java.util.logging.Logger;
  41. public class window {
  42. static int[] a = { 5, 2, 7, 5, 4, 45, 9, 21 };
  43. private JFrame frame;
  44. private static JTextField textField;
  45. String FIO = "";
  46. String GROUP = "";
  47. String FACULTY = "";
  48. int i = 0;
  49. int m = 1;
  50. int pr = 0;
  51. long ans = 0;
  52. long ians = 0;
  53. String tm;
  54. boolean btnpressed = false;
  55. public static boolean ff = false;
  56. /**
  57. * Launch the application.
  58. */
  59. public static void main(String[] args) {
  60. EventQueue.invokeLater(new Runnable() {
  61. public void run() {
  62. try {
  63. window window = new window();
  64. window.frame.setVisible(true);
  65. } catch (Exception e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. });
  70. }
  71. /**
  72. * Create the application.
  73. *
  74. * @throws IOException
  75. * @throws InterruptedException
  76. */
  77. public window() throws IOException, InterruptedException {
  78. initialize();
  79. }
  80. /**
  81. * Initialize the contents of the frame.
  82. *
  83. * @throws IOException
  84. * @throws InterruptedException
  85. */
  86. private void initialize() throws IOException, InterruptedException {
  87. frame = new JFrame();
  88. frame.addWindowStateListener(new WindowStateListener() {
  89. @Override
  90. public void windowStateChanged(WindowEvent e) {
  91. if ((frame.ICONIFIED == 1) || (frame.getExtendedState() == JFrame.NORMAL)) {
  92. frame.toFront();
  93. frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
  94. }
  95. }
  96. });
  97. frame.addWindowListener(new WindowListener() {
  98. public void windowActivated(WindowEvent event) {
  99. }
  100. public void windowClosed(WindowEvent event) {
  101. System.exit(0);
  102. }
  103. public void windowClosing(WindowEvent event) {
  104. }
  105. public void windowDeactivated(WindowEvent event) {
  106. }
  107. public void windowDeiconified(WindowEvent event) {
  108. }
  109. public void windowIconified(WindowEvent event) {
  110. }
  111. public void windowOpened(WindowEvent event) {
  112. }
  113. });
  114. frame.setBounds(100, 100, 1026, 627);
  115. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  116. frame.getContentPane().setLayout(null);
  117. frame.setAlwaysOnTop(true);
  118. frame.toFront();
  119. textField = new JTextField();
  120. textField.setBounds(797, 68, 189, 20);
  121. frame.getContentPane().add(textField);
  122. textField.setColumns(10);
  123. textField.setText(" ");
  124. JButton btnNewButton_1 = new JButton(
  125. "Шаг вперёд 3D"); // пїЅпїЅпїЅпїЅпїЅпїЅ
  126. // пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ
  127. btnNewButton_1.setBounds(797, 165, 176, 23);
  128. frame.getContentPane().add(btnNewButton_1);
  129. /*
  130. * Dimension sSize = Toolkit.getDefaultToolkit ().getScreenSize ();
  131. * frame.setSize(sSize);
  132. */
  133. /*frame.setVisible(true);
  134. frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
  135. frame.toFront();
  136. frame.setResizable(false);
  137. frame.setVisible(false);
  138. frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
  139. frame.toFront();
  140. frame.setVisible(true);*/
  141. /*JPanel panel = new MyPanel();
  142. panel.setBounds(1000, 400, 1000, 1000);
  143. frame.getContentPane().add(panel);*/
  144. int index = 1; // start of search
  145. int temp;
  146. while (index < a.length) { // until the array is fully sorted
  147. boolean nextstep=false;
  148. String st="";
  149.  
  150. for (int h=0; h<a.length; h++) {
  151. st = st+ a[h]+ " ";
  152. //textField.setText(st);
  153. }
  154.  
  155. textField.setText(st);
  156. if (a[index] < a[index - 1]) { // compares nums[index] with
  157. // nums[index-1]. if
  158. // smaller, switch.
  159. temp = a[index];
  160. a[index] = a[index - 1];
  161. a[index - 1] = temp;
  162. index--; // must decrease index to recheck. since they have been
  163. // swapped, the array may still be out of order
  164. if (index == 0) { // prevents index from going lower than 1
  165. index = 1;
  166. }
  167. // Thread.sleep(2000);
  168. } else {
  169. index++; // if sorted, go up
  170. }
  171. }
  172. }
  173. public static int[] gnomeSort(int[] nums) { // takes unsorted array, returns
  174. // sorted
  175. return (nums); // reaching the end of the array- completely sorted,
  176. // returns nums
  177. }
  178. }
P.S Пробовал в качестве извращения делать Thread.Sleep(время), но тогда перестает рисоваться место вывода. Похоже, что дело в моем "процедурном" видении. ООП остается не до конца понятым. Прошу помочь.
Обожаю этот форум! Игнор всегда... Задал простой вопрос, просто сам не дотумкаю...

Решение задачи: «Пошаговое выполнение цикла при нажатии на кнопку»

textual
Листинг программы
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.WindowAdapter;
  4. import java.awt.event.WindowEvent;
  5. import java.io.IOException;
  6.  
  7. public class window {
  8.     static int[] a = {5, 2, 7, 5, 4, 45, 9, 21};
  9.     private static JTextField textField;
  10.  
  11.     boolean btnpressed = false;
  12.     private JFrame frame;
  13.  
  14.  
  15.     public window() throws IOException, InterruptedException {
  16.         initialize();
  17.     }
  18.  
  19.     public static void main(String[] args) {
  20.         EventQueue.invokeLater(() -> {
  21.             try {
  22.                 window window = new window();
  23.                 window.frame.setVisible(true);
  24.             } catch (Exception e) {
  25.                 e.printStackTrace();
  26.             }
  27.         });
  28.     }
  29.  
  30.     private void initialize() throws IOException, InterruptedException {
  31.  
  32.         frame = new JFrame();
  33.  
  34.         frame.addWindowStateListener(e -> {
  35.             frame.toFront();
  36.             frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
  37.         });
  38.         frame.addWindowListener(new WindowAdapter() {
  39.             public void windowClosed(WindowEvent event) {
  40.                 System.exit(0);
  41.             }
  42.         });
  43.         frame.setBounds(100, 100, 1026, 627);
  44.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  45.         frame.getContentPane().setLayout(null);
  46.         frame.setAlwaysOnTop(true);
  47.         frame.toFront();
  48.  
  49.         textField = new JTextField();
  50.         textField.setBounds(797, 68, 189, 20);
  51.         frame.getContentPane().add(textField);
  52.         textField.setColumns(10);
  53.         textField.setText(" ");
  54.  
  55.         JButton btnNewButton_1 = new JButton("Шаг вперёд 3D");
  56.  
  57.         btnNewButton_1.setBounds(797, 165, 176, 23);
  58.         frame.getContentPane().add(btnNewButton_1);
  59.  
  60.  
  61.         btnNewButton_1.addActionListener(e -> {
  62.             btnpressed = true;
  63.         });
  64.         Thread thread = new Thread(() -> {
  65.             int index = 1;
  66.             int temp;
  67.             while (index < a.length) {
  68.                 btnpressed = false;
  69.  
  70.                 String st = "";
  71.  
  72.  
  73.                 if (a[index] < a[index - 1]) {
  74.                     temp = a[index];
  75.                     a[index] = a[index - 1];
  76.                     a[index - 1] = temp;
  77.                     index--;
  78.                     if (index == 0) {
  79.                         index = 1;
  80.                     }
  81.  
  82.                 } else {
  83.                     index++;
  84.                 }
  85.  
  86.                 for (int h = 0; h < a.length; h++) {
  87.                     st = st + a[h] + " ";
  88.                 }
  89.                 System.out.println(st);
  90.                 textField.setText(st);
  91.  
  92.                 while (!btnpressed) {
  93.                     try {
  94.                         Thread.sleep(100);
  95.                     } catch (InterruptedException e) {
  96.                         e.printStackTrace();
  97.                     }
  98.                 }
  99.             }
  100.         });
  101.         thread.start();
  102.     }
  103.  
  104. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

6   голосов , оценка 4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы