代码:
/** * */ package com.niit.syntronized; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; /** * @author: Annie * @date:2016年6月15日 * @description: 打字母游戏(吵醒休眠线程) */ public class WindowTyped extends JFrame implements ActionListener,Runnable{ JTextField inputLetter; Thread giveLetter; JLabel showLetter,showScore; int sleepTime,score; Color c; public WindowTyped() { setLayout(new FlowLayout()); giveLetter = new Thread(this); inputLetter = new JTextField(10); showLetter = new JLabel(" ",JLabel.CENTER); showScore = new JLabel("分数"); showLetter.setFont(new Font("Arial", Font.BOLD, 22)); add(new JLabel("显示字母")); add(showLetter); add(new JLabel("输入所显示的字母(回车)")); add(inputLetter); add(showScore); inputLetter.addActionListener(this); setBounds(100, 100, 450, 200); setVisible(true); validate(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); giveLetter.start(); } @Override public void run() { char c = 'a'; while (true) { showLetter.setText(""+c+" "); c = (char) (c+1); if(c>'z') c='a'; try { Thread.sleep(sleepTime); } catch (InterruptedException e) {} } } public void setSleepTime(int n){ this.sleepTime = n; } @Override public void actionPerformed(ActionEvent e) { String s = showLetter.getText().trim(); String litter = inputLetter.getText().trim(); if(s.equals(litter)){ score++; showScore.setText("得分"+score); validate(); giveLetter.interrupt(); } inputLetter.setText(null); } public static void main(String[] args) { WindowTyped window = new WindowTyped(); window.setTitle("打字母游戏"); window.setSleepTime(2000); } }
效果图: