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

📄 chap12-8.txt

📁 JAVA 学习资源
💻 TXT
字号:
// 程序12-8
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.Font;
import java.applet.Applet;

public class brandishString extends Applet  implements Runnable, MouseListener {
    String str;     		// 要显示的字符串
    char strChars[ ];		// 字符串的字符数组表示
    Thread runner = null;   	// 线程
    boolean threadSuspended;   // 线程的状态	
    int strLength ;        	// 字符串的长度

    static final int REGULAR_WD = 15;	// 字符舞动的宽度
    static final int REGULAR_HT = 36;	// 字符舞动的高度 

    Font regularFont = new Font("Serif", Font.BOLD, REGULAR_HT);    // 设置字体

    public void init( ) {
        str = getParameter("text");  	// 获取HTML文件中参数text的内容
        if (str == null) 
        str = "Hello Java";		// 设置默认参数

        strLength = str.length( );        
        strChars =  new char[strLength];
        str.getChars(0, strLength, strChars, 0); // 获取字符数组

        threadSuspended = false;
        addMouseListener(this);     	// 当前对象自己监视自己
    }

    public void destroy( ) {
        removeMouseListener(this);  	// 将当前对象从监听者表中移出
    }

    public void start( ) {
        runner = new Thread(this);  	// 创建一个线程
        runner.start( );         		// 启动线程
    }

    public synchronized void stop( ) {
        runner = null;
        if (threadSuspended) { 
            threadSuspended = false;
            notify( );
        }
    }

    public void run( ) {
        Thread me = Thread.currentThread( );

        while (runner == me) {
            try {
                Thread.sleep(100);
                synchronized(this) {    // 对当前对象加锁
                    if(threadSuspended) 
                        wait( ); 
                }
            } catch (InterruptedException e){	 }    // 不需要编写异常代码
            repaint( );	// 刷新屏幕
        }
    }

    public void paint(Graphics g) {
        int length = strChars.length;

        for (int i = 0, x = 0; i < length; i++) {
            g.setFont(regularFont);
            int px = (int) (10 * Math.random( ) + x);
            int py = (int) (10 * Math.random( ) + REGULAR_HT);
            g.drawChars(strChars, i, 1, px, py);    	// 输出一个字符
            x += REGULAR_WD;
        }
    }
    
    public synchronized void mousePressed(MouseEvent e) {
        threadSuspended = !threadSuspended;
        if (!threadSuspended)
            notify( );
    }

    public void mouseEntered(MouseEvent e) {  // 鼠标进入小程序,显示Welcome
        showStatus("Welcome");
    }

    public void mouseExited(MouseEvent e) { // 鼠标离开小程序,显示 Bye...
        showStatus("Bye ...");
    }

        //  本程序不需要下面两个方法的功能,因此方法体为空
    public void mouseReleased(MouseEvent e) {   
    }    

    public void mouseClicked(MouseEvent e) {
    }
}

⌨️ 快捷键说明

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