⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 animatepanel.java

📁 char33-2 多线程应用 提供了本书第3章的多线程应用实例的源程序;
💻 JAVA
字号:
import javax.swing.*;
import java.awt.*;
public class AnimatePanel extends JPanel implements Runnable {
	private Thread kicker;
	int[] arr;
	int h1 = -1;
	int h2 = -1;
	SortAlgorithm algorithm;
	AnimatePanel(SortAlgorithm alg) {
		this.algorithm = alg;
		init();
	}
	
	void scramble() {
		int[] a = new int[size().height / 2];
		double f = size().width / (double) a.length;
		for (int i = a.length; --i >= 0;) {
			a[i] = (int) (i * f);
		}
		for (int i = a.length; --i >= 0;) {
			int j = (int) (i * Math.random());
			int t = a[i];
			a[i] = a[j];
			a[j] = t;
		}
		arr = a;
	}
	//设计停止函数
	void pause() {
		pause(-1, -1);
	}
	
	void pause(int H1) {
		pause(H1, -1);
	}
	
	void pause(int H1, int H2) {
		h1 = H1;
		h2 = H2;
		if (kicker != null){
			try {
				SwingUtilities.invokeAndWait(new Runnable() {
					public void run() {
						AnimatePanel.this.repaint();
					}
				});
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			} 
			  catch(Exception ee){
			  	
			  }
			//catch (InvocationTargetException e1) {
				//e1.printStackTrace();
			//}			
		}
		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	//初始化整个环境
	public void init() {
		String at = algorithm.getName();
		scramble();
		setBackground(Color.white);
	}
	//绘制界面
	public void paint(Graphics g) {
		int[] a = arr;
		int y = size().height - 1;
		// 擦去老的线段
		g.setColor(Color.lightGray);
		for (int i = a.length; --i >= 0; y -= 2) {
			g.drawLine(arr[i], y, size().width, y);
		}
		// 绘制线段
		g.setColor(Color.black);
		y = size().height - 1;
		for (int i = a.length; --i >= 0; y -= 2) {
			g.drawLine(0, y, arr[i], y);
		}
		if (h1 >= 0) {
			g.setColor(Color.red);
			y = h1 * 2 + 1;
			g.drawLine(0, y, size().width, y);
		}
		if (h2 >= 0) {
			g.setColor(Color.blue);
			y = h2 * 2 + 1;
			g.drawLine(0, y, size().width, y);
		}
	}
	
	public void update(Graphics g) {
		paint(g);
	}
	//运行算法
	public void run() {
		try {
			algorithm.init();
			algorithm.sort(arr);
		} catch (Exception e) {
		}
	}
	//停止算法的运行
	public synchronized void stop() {
		if (kicker != null) {
			try {
				kicker.stop();
			} catch (IllegalThreadStateException e) {
				// 忽略这个异常
			}
			kicker = null;
		}
		if (algorithm != null) {
			try {
				algorithm.stop();
			} catch (IllegalThreadStateException e) {
				//忽略这个异常
			}
		}
	}
	
	public synchronized void startSort() {
		if (kicker == null || !kicker.isAlive()) {
			scramble();
			//重新绘制界面
			repaint();
			kicker = new Thread(this);
			kicker.start();
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -