线程giveWord每隔6秒钟给出一个汉字,用户使用汉字输入法将该汉字输入到文本框中。WordThread.javaimportjavax.swing.*;publicclassWordThreadextendsThread{charword;intk=19968;JLa...
线程giveWord每隔6秒钟给出一个汉字,用户使用汉字输入法将该汉字输入到文本框中。
WordThread.java
import
javax.swing.*;
public class
WordThread extends Thread
{ char word;
int k=19968;
JLabel com;
WordThread(JLabel com)
{ this.com=com;}
public void run()
{ k=19968;
while(true)
{ word=(char)k;
com.setText(""+word);
try{【代码1】//调用sleep方法使得线程中断6000豪秒}
catch(InterruptedException e){}
k++;
if(k>=29968) k=19968; }}}
ThreadFrame.java
import
java.awt.*;
import
java.awt.event.*;
import
javax.swing.*;
public class
ThreadFrame extends JFrame implements ActionListener
{ JLabel wordLabel;
JButton button;
JTextField inputText,scoreText;
【代码2】//用WordThread声明一个giveWord对象
int score=0;
ThreadFrame()
{ wordLabel=new JLabel("
",JLabel.CENTER);
wordLabel.setFont(new
Font("",Font.BOLD,72));
button=new JButton("开始");
inputText=new JTextField(8);
scoreText=new JTextField(5);
scoreText.setEditable(false);
【代码3】//创建giveWord,将wordLabel传递给WordThread构造方法的参数
button.addActionListener(this);
inputText.addActionListener(this);
add(button,BorderLayout.NORTH);
add(wordLabel,BorderLayout.CENTER);
JPanel southP=new JPanel();
southP.add(new JLabel("输入标签所显示的汉字后回车:"));
southP.add(inputText);
southP.add(scoreText);
add(southP,BorderLayout.SOUTH);
setBounds(100,100,350,180);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==button)
{ if(!(【代码4】)) //giveWord调用方法isAlive()
{ giveWord=new WordThread(wordLabel); }
try
{ 【代码5】//giveWord调用方法start() }
catch(Exception exe){} }
else if(e.getSource()==inputText)
{ if(inputText.getText().equals(wordLabel.getText()))
{ score++;}
scoreText.setText("得分:"+score);
inputText.setText(null); }}}
ThreadWordMainClass.java
public class
ThreadWordMainClass
{ public static void main(String args[])
{ new
ThreadFrame();}}
展开