import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
class WordPanel extends JPanel implements Runnable{
private Thread thread = null;
private int level = 1;
private Font font = new Font("宋体",Font.ITALIC+Font.BOLD,24);
private Color color = Color.BLUE;
public static final int x = 10;
private int y = 0;
private char word;//下落的字母
private static Random rand = new Random();
public void setY(int y){
this.y = y;
}
public void setWord(char word){
this.word = word;
}
public char getWord(){
return this.word;
}
public static char newChar(){
return (char)(97+rand.nextInt(26));
}
public WordPanel(){
word = newChar();
thread = new Thread(this);
thread.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
g.setColor(color);
g.drawString(String.valueOf(word),x,y);
}
public void run(){
while (true){
try {
Thread.sleep(1000);
this.repaint();
if (y>=this.getHeight()){
y = 0;
word = this.newChar();
}else
y+=20;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
class WordGame extends JFrame{
private WordPanel[] words = new WordPanel[10];
class Listener extends KeyAdapter{
public void keyTyped(KeyEvent e) {
char input = e.getKeyChar();
for (int i = 0; i<words.length; i++){
if ( input==words[i].getWord() ){
words[i].setWord(WordPanel.newChar());
words[i].setY(0);
words[i].repaint();
break;
}
}
}
}
public WordGame(String title){
super(title);//思考
Container c = this.getContentPane();
c.setLayout(new GridLayout(1,words.length));
this.addKeyListener( new Listener() );
for (int i = 0; i<words.length; i++){
words[i] = new WordPanel();
c.add(words[i]);
}
this.setSize( new Dimension(300,300) );
this.setVisible(true);
}
public static void main(String[] args){
WordGame game = new WordGame("开个窗口掉字母");
}
}
温馨提示:内容为网友见解,仅供参考