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

📄 typetrainapplet.java

📁 java的打字程序
💻 JAVA
字号:
package chapter11;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.io.*;
import java.applet.AudioClip;

public class TypeTrainApplet extends JApplet {
    boolean isStandalone = false;
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel infoPnl = new JPanel();
    JButton jButton1 = new JButton();
    JButton jButton2 = new JButton(); //Construct the applet
    JButton jButton3 = new JButton("保存");
    JLabel totalLbl_1 = new JLabel("总数");
    JLabel totalLbl_2 = new JLabel(""); //计算总共下落的字母数标签
    JLabel rightLbl_1 = new JLabel("正确数");
    JLabel rightLbl_2 = new JLabel(""); //计算正确击中的字母数标签
    JLabel errorLbl_1 = new JLabel("失败数");
    JLabel errorLbl_2 = new JLabel(""); //计算未击中的字母数标签

    Canvas canvas = new Canvas(); //画板

    ImageIcon startIcon = new ImageIcon(TypeTrainApplet.class.getResource(
        "start.gif"));
    ImageIcon pauseIcon = new ImageIcon(TypeTrainApplet.class.getResource(
        "pause.gif"));
    ImageIcon stopIcon = new ImageIcon(TypeTrainApplet.class.getResource(
        "stop.gif"));

    AudioClip hitSound; //音效

    int stepLen;
    int stepInterval;
    int columnCount;
    int generateInterval;

    volatile int totalCount = 0; //总数计数器
    volatile int rightCount = 0; //正确数计数器
    volatile int errorCount = 0; //错误数计数器

    int colWidth; //每栏的宽度
    volatile char pressKeyChar; //记录按下的按键
    int statusCode = 0; //1运行态、2暂停态 0 停止态
    boolean isClose = false;//用于标识Applet窗口有没有关闭

    public TypeTrainApplet() {}

    //Initialize the applet
    public void init() {
        try {
            stepLen = Integer.parseInt(this.getParameter("stepLen", "2"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            stepInterval = Integer.parseInt(this.getParameter("stepInterval",
                "50"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            columnCount = Integer.parseInt(this.getParameter("columnCount",
                "10"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            generateInterval = Integer.parseInt(this.getParameter(
                "generateInterval", "500"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }

        hitSound = getAudioClip( (TypeTrainApplet.class).getResource(
            "hit.wav")); //加载音效文件
    }

    //Get a parameter value
    public String getParameter(String key, String def) {
        return isStandalone ? System.getProperty(key, def) :
            (getParameter(key) != null ? getParameter(key) : def);
    }

    //Component initialization
    private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        infoPnl.setBackground(Color.cyan);
        infoPnl.setLayout(new GridLayout(9, 1));
        this.addKeyListener(new TypeTrainApplet_this_keyAdapter(this));
        jButton1.setIcon(startIcon);
        jButton2.setIcon(stopIcon);
        jButton2.setEnabled(false);
        jButton1.addActionListener(new TypeTrainApplet_jButton1_actionAdapter(this));
        jButton2.addActionListener(new TypeTrainApplet_jButton2_actionAdapter(this));
        jButton3.addActionListener(new
                                   TypeTrainApplet_jButton3_actionAdapter(this));
        infoPnl.add(jButton1);
        infoPnl.add(jButton2);
        infoPnl.add(jButton3);
        infoPnl.add(totalLbl_1);
        infoPnl.add(totalLbl_2);
        infoPnl.add(rightLbl_1);
        infoPnl.add(rightLbl_2);
        infoPnl.add(errorLbl_1);
        infoPnl.add(errorLbl_2);
        getContentPane().add(infoPnl, BorderLayout.EAST); this.getContentPane().
            add(canvas, java.awt.BorderLayout.CENTER); canvas.setBackground(
                Color.yellow);
    }

    //Get Applet information
    public String getAppletInfo() {
        return "Applet Information";
    }

    //Get parameter info
    public String[][] getParameterInfo() {
        java.lang.String[][] pinfo = { {
            "stepLen", "int", "步长"}, {
            "stepInterval", "int", "间隔"}, {
            "columnCount", "int", "栏数"}, {
            "generateInterval", "int", "间隔"},
        };
        return pinfo;
    }

    /**
     * 将统计结果画到界面上
     */
    private void drawResult() {
        totalLbl_2.setText("" + totalCount);
        rightLbl_2.setText("" + rightCount);
        errorLbl_2.setText("" + errorCount);
    }

    /**
     * 重置现场
     */
    private void resetGame() {
        totalCount = 0;
        rightCount = 0;
        errorCount = 0;
        drawResult();
    }

    //Start the applet
    public void start() {
        isClose = false;
    }

    public void stop() {
        statusCode = 0;//停止游戏
        isClose = true;//窗口关闭
    }

    public void destroy() {
    }

    /**获取用户点击按键所对应的字符*/
    public void this_keyPressed(KeyEvent e) {
        if (!e.isActionKey()) {
            pressKeyChar = e.getKeyChar();
        }
    }

    public void jButton1_actionPerformed(ActionEvent e) {
        if (statusCode == 0) { //从结束->开始
            resetGame();
            statusCode = 1;
            colWidth = canvas.getWidth() / columnCount;
            GenerateDropThread gdThread = new GenerateDropThread(); //总控线程运行
            gdThread.start();
            jButton1.setIcon(pauseIcon);
            jButton2.setEnabled(true);
        } else if (statusCode == 1) { //从运行->暂停
            statusCode = 2;
            jButton1.setIcon(startIcon);
        } else { //从暂停->运行
            statusCode = 1;
            jButton1.setIcon(pauseIcon);
            synchronized (canvas) {
                canvas.notifyAll();
            }
        }
        this.requestFocus();
    }

    public void jButton2_actionPerformed(ActionEvent e) {
        statusCode = 0;
        synchronized (canvas) {
            canvas.notifyAll();
        }
        jButton2.setEnabled(false);
        jButton1.setIcon(startIcon);
    }

    public void jButton3_actionPerformed(ActionEvent e) {
        FileWriter fw = null;
        try {
            File file = new File("d:\\result.txt");
            fw = new FileWriter(file);
            fw.write("总数:" + totalCount + "\n");
            fw.write("正确数:" + rightCount + "\n");
            fw.write("失败数:" + errorCount);
            fw.flush();
            JOptionPane.showMessageDialog(this, "成绩成功保存到d:\result.txt中", "信息",
                                          JOptionPane.OK_OPTION);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException ex1) {
                ex1.printStackTrace();
            }
        }
    }

    /**下落字体线程*/
    //////////////////////////////////////////////////////////////////////////////
    private class DropCharThread extends Thread {
        char c; //对应的字符
        int colIndex; //在哪列下落
        int x, y; //行列的坐标
        private static final int ACTION_DRAW_FONT = 1; //画字符
        private static final int ACTION_CLEAR_FONT = 2; //清字符
        public DropCharThread(char c, int colIndex) {
            this.c = c;
            this.colIndex = colIndex;
            this.x = (colIndex - 1) * colWidth + colWidth / 2; //所在的横坐标
        }

        public void run() {
            draw(ACTION_DRAW_FONT);
            try {
                while (c != pressKeyChar && y < canvas.getHeight() &&
                       statusCode != 0) {
                    synchronized (canvas) {
                        while (statusCode == 2) {
                            canvas.wait();
                        }
                    }
                    draw(ACTION_CLEAR_FONT);
                    y += stepLen;
                    draw(ACTION_DRAW_FONT);
                    Thread.sleep(stepInterval);
                }
            } catch (InterruptedException ex) {
            }

            if (!isClose) {
                draw(ACTION_CLEAR_FONT);
                if (statusCode != 0) { //游戏没有停止
                    totalCount++; //统计总数
                    if (y < canvas.getHeight()) {
                        hitSound.play();
                        rightCount++; //打中
                    } else {
                        errorCount++; //打不中
                    }
                    drawResult();
                }
            }
        }

        /**
         * <b>功能说明:</b><br>
         * 画字母
         * @param actionType 1:画字母 2: 清除字母
         */
        private void draw(int actionType) {
            synchronized (canvas) { //必须对资源canvas进行同步,否则会产生线程不安全
                Graphics g = canvas.getGraphics();
                if (actionType == ACTION_CLEAR_FONT) {
                    g.setXORMode(canvas.getBackground()); //清除
                }
                g.setFont(new Font("Times New Roman", Font.PLAIN, 12));
                g.drawString("" + c, x, y);
            }
        }
    }

    //////////////////////////////////////////////////////////////////////////////

    /**创建下落字体线程的主线程*/
    //////////////////////////////////////////////////////////////////////////////
    private class GenerateDropThread extends Thread {
        Random random = new Random(); //随机数
        public void run() {
            try {
                while (statusCode != 0) { //产生下落线程
                    synchronized (canvas) {
                        while (statusCode == 2) {
                            canvas.wait();
                        }
                    }
                    DropCharThread dropCharThread = new DropCharThread(
                        getRandomChar(),
                        random.nextInt(columnCount) + 1);
                    dropCharThread.start();
                    Thread.sleep(generateInterval);
                }
            } catch (InterruptedException ex) {
            }
        }

        /**
         * <b>功能说明:</b><br>
         * 返回一个随机字符
         * @return 随机字符
         */
        private char getRandomChar() {
            int temp = 97 + random.nextInt(26);
            return (char) temp;
        }
    }
//////////////////////////////////////////////////////////////////////////////

}

class TypeTrainApplet_jButton3_actionAdapter implements ActionListener {
    private TypeTrainApplet adaptee;
    TypeTrainApplet_jButton3_actionAdapter(TypeTrainApplet adaptee) {
        this.adaptee = adaptee; }

    public void actionPerformed(ActionEvent e) {
        adaptee.jButton3_actionPerformed(e); }}

class TypeTrainApplet_jButton2_actionAdapter implements ActionListener {
    private TypeTrainApplet adaptee;
    TypeTrainApplet_jButton2_actionAdapter(TypeTrainApplet adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {

        adaptee.jButton2_actionPerformed(e);
    }
}

class TypeTrainApplet_jButton1_actionAdapter implements ActionListener {
    private TypeTrainApplet adaptee;
    TypeTrainApplet_jButton1_actionAdapter(TypeTrainApplet adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {
        adaptee.jButton1_actionPerformed(e);
    }
}

class TypeTrainApplet_this_keyAdapter extends KeyAdapter {
    private TypeTrainApplet adaptee;
    TypeTrainApplet_this_keyAdapter(TypeTrainApplet adaptee) {
        this.adaptee = adaptee;
    }

    public void keyPressed(KeyEvent e) {
        adaptee.this_keyPressed(e);
    }
}

⌨️ 快捷键说明

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