打字母游戏

来源:互联网 发布:小牛在线网络借贷 编辑:程序博客网 时间:2024/04/27 15:42

利用线程控制字母出现的时间,训练用户寻找键盘上字母的快速能力。

随机出现26位小写字母的一个 输入后按回车即可。

如果输入正确分数+1,字母立刻改变。如果输入错误,分数-1,字母根据线程设置的sleep时间改变

package Example12_10;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Example12_10 {public static void main(String args[]){WindowTyped win=new WindowTyped();win.setTitle("打字母游戏");win.setSleepTime(3000);}}class WindowTyped extends JFrame implements ActionListener,Runnable{JTextField inputLetter;Thread giveLetter;JLabel showLetter,showScore;int sleepTime,score;public void setSleepTime(int sleepTime){this.sleepTime=sleepTime;}WindowTyped(){setLayout(new FlowLayout());giveLetter=new Thread(this);inputLetter =new JTextField(6);showLetter=new JLabel(" ",JLabel.CENTER);showScore=new JLabel("分数:");showScore.setFont(new Font("宋体",Font.PLAIN,18));showScore.setForeground(Color.red);showLetter.setFont(new Font("Arial",Font.BOLD,22));showLetter.setForeground(Color.blue);add(new JLabel("显示字母:"));add(showLetter);add(new JLabel("输入所显示的字母(回车)"));add(inputLetter);add(showScore);inputLetter.addActionListener(this);setBounds(100,100,400,280);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);giveLetter.start();}public void run(){while(true){int x=(int)(Math.random()*26)+0;//随机数showLetter.setText(""+(char)((char)x+'a')+"");validate();try{Thread.sleep(sleepTime);}catch(InterruptedException e){}}}public void actionPerformed(ActionEvent e){String s=showLetter.getText().trim();String letter=inputLetter.getText().trim();if(s.equals(letter)){score++;showScore.setText("得分"+score);inputLetter.setText(null);validate();giveLetter.interrupt();}}}

这是结果

1 0
原创粉丝点击