冒泡排序图形化界面java代码
时间: 2023-07-09 09:23:17 浏览: 97
课程设计《冒泡排序和快速排序的交互动画》图形化显示
以下是一个简单的冒泡排序的图形化界面 Java 代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BubbleSortGUI extends JFrame implements ActionListener {
private int[] data;
private JButton btnSort, btnShuffle;
private SortPanel sortPanel;
public BubbleSortGUI() {
setTitle("Bubble Sort GUI");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 初始化数据
data = new int[] { 5, 2, 9, 1, 5, 6, 3 };
sortPanel = new SortPanel(data);
add(sortPanel, BorderLayout.CENTER);
// 添加按钮
btnSort = new JButton("Sort");
btnSort.addActionListener(this);
btnShuffle = new JButton("Shuffle");
btnShuffle.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(btnSort);
buttonPanel.add(btnShuffle);
add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSort) {
sortData();
} else if (e.getSource() == btnShuffle) {
shuffleData();
}
}
private void sortData() {
for (int i = data.length - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
if (data[j] > data[j + 1]) {
int temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
sortPanel.repaint();
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
}
private void shuffleData() {
for (int i = 0; i < data.length; i++) {
int j = (int) (Math.random() * data.length);
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
sortPanel.repaint();
}
private class SortPanel extends JPanel {
private static final int BAR_WIDTH = 25;
private int[] data;
public SortPanel(int[] data) {
this.data = data;
setPreferredSize(new Dimension(data.length * BAR_WIDTH, 200));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < data.length; i++) {
int x = i * BAR_WIDTH;
int height = data[i] * 20;
g.fillRect(x, getHeight() - height, BAR_WIDTH - 2, height);
}
}
}
public static void main(String[] args) {
new BubbleSortGUI();
}
}
```
该代码实现了一个简单的冒泡排序的图形化界面,其中通过 `SortPanel` 类绘制条形图来表示数据,通过按钮实现排序和打乱数据的功能。在排序过程中,通过调用 `repaint()` 方法来重新绘制 `SortPanel`,从而在界面上实时显示排序的过程。由于界面操作需要在事件线程中完成,因此在排序过程中需要让线程暂停一段时间,以允许事件线程进行绘制操作。
阅读全文