JPanel 仅在 for 循环完成后更新



我正在制作一个排序可视化工具,一切正常,直到我尝试在按钮上实现排序功能。问题是,当从按钮调用排序函数时,屏幕不会刷新,直到 for 循环完成(通常,排序函数可以完美运行(。

主要:

public class Main {
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
}
}

测试类:

public class Test implements ActionListener {
public static int WIN_WIDTH = 1500;
public static int WIN_HEIGHT = 750;
JButton shuffleButton;
JButton bubbleSort;
JFrame window;
SortArray sortArray;
public Test() throws InterruptedException {
shuffleButton = new JButton();
shuffleButton.setBounds(WIN_WIDTH + 10, 0, 160, 100);
shuffleButton.setText("Shuffle!");
bubbleSort = new JButton();
bubbleSort.setBounds(WIN_WIDTH + 10, 200, 160, 100);
bubbleSort.setText("Bubble sort!");

window = new JFrame("Sort Visualizer");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(WIN_WIDTH + 200, WIN_HEIGHT);
window.setVisible(true);
sortArray = new SortArray();
window.add(shuffleButton);
window.add(bubbleSort);
window.add(sortArray);
sortArray.repaint();
sortArray.bubble_sort();
shuffleButton.addActionListener(this);
bubbleSort.addActionListener(this);

}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == shuffleButton){
sortArray.shuffleArray();
}else if(e.getSource() == bubbleSort){
try {
sortArray.bubble_sort();
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
}
}
}

排序数组类:

public class SortArray extends JPanel {
private static int NM_NM = WIN_WIDTH;
public static int BAR_WIDTH = WIN_WIDTH / NM_NM;
private int[] array;
public SortArray() throws InterruptedException {
shuffleArray();
}
public void shuffleArray(){
Random rng = new Random();
array = new int[NM_NM];
for (int i = 0; i < array.length; i++) {
repaint();
array[i] = rng.nextInt(WIN_HEIGHT);
}
}
public void bubble_sort() throws InterruptedException {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
//bubble sort
System.out.println("sorting...");
Boolean not_sorted = true;
while (not_sorted) {
TimeUnit.MICROSECONDS.sleep(1);
not_sorted = false;
for (int i = 1; i < array.length; i++) {
if (array[i] > array[i - 1]) {
int temp = array[i];
array[i] = array[i-1];
array[i-1] = temp;
not_sorted = true;
repaint();
}
}
if (!not_sorted) {
break;
}
}
return null;
}
};
worker.execute();
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D graphics2D = (Graphics2D) g;
super.paintComponent(graphics2D);
for (int j = 0; j < array.length; j++) {
graphics2D.setColor(Color.BLACK);
graphics2D.fillRect(j * BAR_WIDTH, 0, BAR_WIDTH, array[j]);
}
}

}

好的,我解决了它,基本上我所做的就是用 SwingWorker 包围 bubbleSort(( 函数中的所有命令,然后执行它。(这将创建一个后台线程(。我编辑了正确的代码。

最新更新