ex_20.java

来自「JAVA分布式程序学习的课件(全英文)」· Java 代码 · 共 70 行

JAVA
70
字号
// Based on the Holmes text
// chap_11\Ex_9.java
// program to display a digital clock allowing the calculation of 
// the time and displaying the value to run in its own thread of 
// execution

import java.applet.*;
import java.awt.*;
import java.util.*;

public class Ex_20 extends Applet implements Runnable
{
	Thread appletThread;	
		
	Font font = new Font("Monospaced",Font.BOLD,16);	

	int hours, mins, secs;
	
	// override the init() method to initialize and start 
	// a thread of execution
	public void init()
	{
		if (appletThread == null)
		{
			appletThread = new Thread(this);
			appletThread.start(); // start from class Thread
		}
	}
	
	// calculate the time of day, and call the repaint method to 
	// display the time
	public void run() // implemented from the abstract class Runnable
	{
		while (true)
		{
			Calendar time=Calendar.getInstance();
			
			hours = time.get(Calendar.HOUR);
			mins = time.get(Calendar.MINUTE);
			secs = time.get(Calendar.SECOND);		
			
			repaint();

			// generate a short pause by letting the thread sleep
			try{Thread.sleep(1000);} 
			catch(InterruptedException i){System.exit(1);}
		}
	}

	// override the destroy() method to stop the execution of the thread
	// and nullify the thread
	public void destroy()
	{
		if (appletThread != null)
		{
			appletThread.stop(); // deprecated, see new API doc
			appletThread = null;
		}
	}

	// display the time in the applet's window
	public void paint(Graphics g)
	{
		g.setFont(font);
		g.drawString(String.valueOf(hours)+":"+
			         String.valueOf(mins)+":"+
					 String.valueOf(secs),50,50);
	}
}

⌨️ 快捷键说明

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