Пошаговое выполнение цикла при нажатии на кнопку - Java
Формулировка задачи:
Здравствуйте!
Не знаю, как реализовать пошаговое выполнение цикла при нажатии на кнопку. Среда Eclipse Neon.2
По задаче, как видите, имеется гномья сортировка массива. Изначально был консольный вариант, необходимо переделать под GUI с оговоренными выше условиями.
Просьба не ругаться на лишние импорты, т.к WindowBuilder стоит, но не отображается в списке компонентов ===> приходится все элементы прописывать ручками.
package dlab6_1;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.Toolkit;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class window {
static int[] a = { 5, 2, 7, 5, 4, 45, 9, 21 };
private JFrame frame;
private static JTextField textField;
String FIO = "";
String GROUP = "";
String FACULTY = "";
int i = 0;
int m = 1;
int pr = 0;
long ans = 0;
long ians = 0;
String tm;
boolean btnpressed = false;
public static boolean ff = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
window window = new window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* @throws IOException
* @throws InterruptedException
*/
public window() throws IOException, InterruptedException {
initialize();
}
/**
* Initialize the contents of the frame.
*
* @throws IOException
* @throws InterruptedException
*/
private void initialize() throws IOException, InterruptedException {
frame = new JFrame();
frame.addWindowStateListener(new WindowStateListener() {
@Override
public void windowStateChanged(WindowEvent e) {
if ((frame.ICONIFIED == 1) || (frame.getExtendedState() == JFrame.NORMAL)) {
frame.toFront();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
});
frame.addWindowListener(new WindowListener() {
public void windowActivated(WindowEvent event) {
}
public void windowClosed(WindowEvent event) {
System.exit(0);
}
public void windowClosing(WindowEvent event) {
}
public void windowDeactivated(WindowEvent event) {
}
public void windowDeiconified(WindowEvent event) {
}
public void windowIconified(WindowEvent event) {
}
public void windowOpened(WindowEvent event) {
}
});
frame.setBounds(100, 100, 1026, 627);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setAlwaysOnTop(true);
frame.toFront();
textField = new JTextField();
textField.setBounds(797, 68, 189, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField.setText(" ");
JButton btnNewButton_1 = new JButton(
"Шаг вперёд 3D"); // пїЅпїЅпїЅпїЅпїЅпїЅ
// пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ
btnNewButton_1.setBounds(797, 165, 176, 23);
frame.getContentPane().add(btnNewButton_1);
/*
* Dimension sSize = Toolkit.getDefaultToolkit ().getScreenSize ();
* frame.setSize(sSize);
*/
/*frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.toFront();
frame.setResizable(false);
frame.setVisible(false);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.toFront();
frame.setVisible(true);*/
/*JPanel panel = new MyPanel();
panel.setBounds(1000, 400, 1000, 1000);
frame.getContentPane().add(panel);*/
int index = 1; // start of search
int temp;
while (index < a.length) { // until the array is fully sorted
boolean nextstep=false;
String st="";
for (int h=0; h<a.length; h++) {
st = st+ a[h]+ " ";
//textField.setText(st);
}
textField.setText(st);
if (a[index] < a[index - 1]) { // compares nums[index] with
// nums[index-1]. if
// smaller, switch.
temp = a[index];
a[index] = a[index - 1];
a[index - 1] = temp;
index--; // must decrease index to recheck. since they have been
// swapped, the array may still be out of order
if (index == 0) { // prevents index from going lower than 1
index = 1;
}
// Thread.sleep(2000);
} else {
index++; // if sorted, go up
}
}
}
public static int[] gnomeSort(int[] nums) { // takes unsorted array, returns
// sorted
return (nums); // reaching the end of the array- completely sorted,
// returns nums
}
}
P.S Пробовал в качестве извращения делать Thread.Sleep(время), но тогда перестает рисоваться место вывода.
Похоже, что дело в моем "процедурном" видении. ООП остается не до конца понятым.
Прошу помочь.
Обожаю этот форум! Игнор всегда...
Задал простой вопрос, просто сам не дотумкаю...
Решение задачи: «Пошаговое выполнение цикла при нажатии на кнопку»
textual
Листинг программы
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
public class window {
static int[] a = {5, 2, 7, 5, 4, 45, 9, 21};
private static JTextField textField;
boolean btnpressed = false;
private JFrame frame;
public window() throws IOException, InterruptedException {
initialize();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
window window = new window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
private void initialize() throws IOException, InterruptedException {
frame = new JFrame();
frame.addWindowStateListener(e -> {
frame.toFront();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
});
frame.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent event) {
System.exit(0);
}
});
frame.setBounds(100, 100, 1026, 627);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setAlwaysOnTop(true);
frame.toFront();
textField = new JTextField();
textField.setBounds(797, 68, 189, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField.setText(" ");
JButton btnNewButton_1 = new JButton("Шаг вперёд 3D");
btnNewButton_1.setBounds(797, 165, 176, 23);
frame.getContentPane().add(btnNewButton_1);
btnNewButton_1.addActionListener(e -> {
btnpressed = true;
});
Thread thread = new Thread(() -> {
int index = 1;
int temp;
while (index < a.length) {
btnpressed = false;
String st = "";
if (a[index] < a[index - 1]) {
temp = a[index];
a[index] = a[index - 1];
a[index - 1] = temp;
index--;
if (index == 0) {
index = 1;
}
} else {
index++;
}
for (int h = 0; h < a.length; h++) {
st = st + a[h] + " ";
}
System.out.println(st);
textField.setText(st);
while (!btnpressed) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}