import java.awt.event.*; 
import javax.swing.*; 
import java.lang.*; 
import java.awt.*; 
public class JinWu extends KeyAdapter 

static int i,j,k,l; 
static JFrame f=new JFrame(); 
String str[]={"4","8","6","2"}; 
JButton b[]=new JButton[str.length]; 
public JinWu() 

Initbutton(); 
f.setLayout(new FlowLayout()); 
f.setSize(600,200); 
Init(); 

public void Init() 

i=(int)(Math.random() * 100) % 4; 
f.getContentPane().add(b[i]); 
b[i].addKeyListener(this); 
 j=(int)(Math.random() * 100) % 4; 
f.getContentPane().add(b[j]); 
b[j].addKeyListener(this); 
 k=(int)(Math.random() * 100) % 4; 
f.getContentPane().add(b[k]); 
b[k].addKeyListener(this); 
 l=(int)(Math.random() * 100) % 4; 
f.getContentPane().add(b[l]); 
b[l].addKeyListener(this); 

    public void Initbutton() 

for(int i=0;i <4;i++) 

b[i]=new JButton(str[i]); 


public void keyPressed(KeyEvent e) 

b[i].requestFocus(); 
if(e.getKeyCode()==4) 

b[i].setVisible(false); 
b[j].requestFocus(); 
if(e.getKeyCode()==8) 
    { 
   b[j].setVisible(false); 
   b[k].requestFocus(); 
   if(e.getKeyCode()==6) 
           { 
          b[k].setVisible(false); 
          b[l].requestFocus(); 
          if(e.getKeyCode()==2) 
          { 
           b[l].setVisible(false); 
           Init(); 
          } 
        } 
     } 
 } 
    } 
public static void main(String [] args) 

JinWu jw=new JinWu(); 
f.setVisible(true); 


模仿的是劲舞团的游戏
我是想用4,8,6,2,控制,出来一排键后按下对应的键即可消除其,但是总是出不来四个键,有的时候出来三个 有的时候出来两个,看看是怎么回事啊? 

解决方案 »

  1.   

    public void Init()  
    {  
    i=(int)(Math.random() * 100) % 4;  
    f.getContentPane().add(b[i]);  
    b[i].addKeyListener(this);  
     j=(int)(Math.random() * 100) % 4;  
    f.getContentPane().add(b[j]);  
    b[j].addKeyListener(this);  
     k=(int)(Math.random() * 100) % 4;  
    f.getContentPane().add(b[k]);  
    b[k].addKeyListener(this);  
     l=(int)(Math.random() * 100) % 4;  
    f.getContentPane().add(b[l]);  
    b[l].addKeyListener(this);  
    }  
    你用这个方法来产生的按扭本来就是随机的(i,j,k,l只是四个随机数(0,1,2,3中的一个)),当他们取的数值b[?]相同时就把先产生的按扭覆盖了.当然会出现你说的那种情况啊