test.java

来自「《Java2图形设计卷II:Swing》配套光盘源码」· Java 代码 · 共 68 行

JAVA
68
字号
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
	private JProgressBar progressBar = new JProgressBar();
	private JButton startButton = new JButton("start");

	public void init() {
		Container contentPane = getContentPane();

		contentPane.setLayout(new FlowLayout());
		contentPane.add(startButton);
		contentPane.add(progressBar);

		progressBar.setStringPainted(true);

		startButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				(new UpdateThread()).start();
			}
		});
	}
	class UpdateThread extends Thread {
		Runnable update, finish;
		int value, min, max, increment;

		public UpdateThread() {
			max = progressBar.getMaximum(); 
			min = progressBar.getMinimum();

			update = new Runnable() {
				public void run() {
					value = progressBar.getValue() + increment;
					updateProgressBar(value);
				}
			};
			finish = new Runnable() {
				public void run() {
					updateProgressBar(min);
				}
			};
		}
		public void run() {
			startButton.setEnabled(false);

			while(value + increment <= max) {
				simulateTimeConsumingActivity();
				SwingUtilities.invokeLater(update);
			}
			SwingUtilities.invokeLater(finish);
			startButton.setEnabled(true);
		}
		private void updateProgressBar(int value) {
			progressBar.setValue(value);
		}
		private void simulateTimeConsumingActivity() {
			try {
				Thread.currentThread().sleep(1000);
				increment = (max - min) / 10;
			}
			catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

⌨️ 快捷键说明

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