用java写一个冒泡排序UI动画
时间: 2023-12-21 08:07:41 浏览: 70
好的,我可以为您提供一个简单的冒泡排序UI动画,基于Java Swing编写。以下是代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BubbleSortUI extends JFrame implements ActionListener {
private JPanel panel;
private JTextField inputField;
private JTextArea outputArea;
private JButton sortButton;
private int[] array;
public BubbleSortUI() {
super("Bubble Sort UI");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new GridLayout(3, 1));
inputField = new JTextField();
panel.add(inputField);
outputArea = new JTextArea();
panel.add(outputArea);
sortButton = new JButton("Sort");
sortButton.addActionListener(this);
panel.add(sortButton);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sortButton) {
String input = inputField.getText();
String[] inputArray = input.split("\\s+");
array = new int[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
array[i] = Integer.parseInt(inputArray[i]);
}
bubbleSort();
}
}
private void bubbleSort() {
int n = array.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (array[j - 1] > array[j]) {
//交换
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
//更新UI
outputArea.setText("");
for (int k = 0; k < n; k++) {
outputArea.append(array[k] + " ");
}
try {
Thread.sleep(500); //延迟0.5秒
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
new BubbleSortUI();
}
}
```
这个程序允许您输入一组数字,并对其进行冒泡排序。当数组中的两个元素交换位置时,程序会更新UI并在0.5秒后继续执行。
阅读全文