編寫一個Java應用程序,在主線程中再創建一個Frame類型的窗口,在該窗口中再創建1個線程giveWord。線程giveWord每隔2秒鐘給出一個漢字,用戶使用一種漢字輸入法將該漢字輸入到文本框中。
WordThread.java
import java.awt.*;
public class WordThread extends Thread
{
int time = 6000;
char word;
int k=19968;
Label com;
WordThread(Label com)
{ this.com=com;
}
public void run()
{
k=19968;
while(true)
{
word=(char)k;
com.setText(""+word);
try{ //【代碼1】//調用sleep方法使得線程中斷6000豪秒
//sleep(6000);
//更改爲線程中斷time毫秒
sleep(time);
}
catch(InterruptedException e){}
k++;
if(k>=29968) k=19968;
}
}
public void setTime(int n) {
time = n;
}
}
ThreadFrame.java
import java.awt.*;
import java.awt.event.*;
public class ThreadFrame extends Frame implements ActionListener {
Label wordLabel;
Button button;
TextField inputText, scoreText;
WordThread giveWord;// 【代碼2】// 用WordThread聲明一個giveWord對象
int score = 0;
ThreadFrame() {
wordLabel = new Label(" ", Label.CENTER);
wordLabel.setFont(new Font("", Font.BOLD, 72));
button = new Button("開始");
inputText = new TextField(3);
scoreText = new TextField(5);
scoreText.setEditable(false);
// 【代碼3】//創建giveWord,將wordLabel傳遞給WordThread構造方法的參數
giveWord = new WordThread(wordLabel);
button.addActionListener(this);
inputText.addActionListener(this);
add(button, BorderLayout.NORTH);
add(wordLabel, BorderLayout.CENTER);
Panel southP = new Panel();
southP.add(new Label("輸入標籤所顯示的漢字後回車:"));
southP.add(inputText);
southP.add(scoreText);
add(southP, BorderLayout.SOUTH);
setBounds(100, 100, 350, 180);
setVisible(true);
validate();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{ if(!(giveWord.isAlive())) //giveWord調用方法isAlive()
{
giveWord=new WordThread(wordLabel);
}
try
{ //【代碼5】//giveWord調用方法start()
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();
}
}
項目展示: