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,控制,出来一排键后按下对应的键即可消除其,但是总是出不来四个键,有的时候出来三个 有的时候出来两个,看看是怎么回事啊?
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,控制,出来一排键后按下对应的键即可消除其,但是总是出不来四个键,有的时候出来三个 有的时候出来两个,看看是怎么回事啊?
f.getContentPane().add(b[1]);
f.getContentPane().add(b[1]);
f.getContentPane().add(b[1]);
f.getContentPane().add(b[1]);
}这样 只是重复添加一个实例 只有一个按钮添加进去了 同样 你获得的随机数 ijkl 可能重复 就导致了按钮不全
要做个随机 重复判断