java如何做一个随机抽取学号小程序
的有关信息介绍如下:
上学的时候,大家有过被老师点名的回忆。如果再程序班,老师喜欢用程序抽去学号,然后点名签到,这种方法点名就看个人运气(大学好多老师不会像中学那样都记得学生的名字的)。现在就带大家做做这个简单的学号点名小程序。
程序代码:http://pan.baidu.com/s/1eQmrI7o
功能:根据你输入的学号总数,点击开始,中间的结果就根据学号的总数不停变化,点击停止,结果停止变动,
分析:从上面的图中我们可以打出,学号小点名程序需要一个输入框,一个现实结果的lable,两个按钮,以及一个固定大小的窗体。所以我们先定义好这些变量并且new他们出来。
JTextField num; //输入总人数
JButton start,stop; // 开始、停止按钮
JLabel rs; //显示结果
JPanel jp1,jp;
static boolean isSotp = true; //判断当前状态
public number() {
num = new JTextField(15);
start = new JButton("开始");
stop = new JButton("停止");
rs = new JLabel("0");
jp = new JPanel();
jp1 = new JPanel();
start.addActionListener(this); //添加监听
stop.addActionListener(this);
this.add(num,BorderLayout.NORTH);
jp1.add(rs);
this.add(jp1,BorderLayout.CENTER);
FlowLayout layout = new FlowLayout();//面板布局
layout.setAlignment(FlowLayout.CENTER);
jp1.setLayout(layout);
jp.setLayout(layout);
jp.add(start);
jp.add(stop);
rs.setFont(new Font("宋体", 1, 50));//设置结果样式
rs.setForeground(Color.BLUE);
this.add(jp,BorderLayout.SOUTH);
}
然后添加随机数,这个随机数是随机获得学号的:
public static int getnumber(int n){ //根据你输入的总人数返回随机在人数范围内的一个学号
Random r = new Random();
int r1 = r.nextInt(n + 1);
return r1;
}
新建线程内部类:利用线程让“学号”动起来。
class thr extends Thread{
private JLabel rs;
int n;
thr(JLabel rs,int n){
this.rs = rs;
this.n = n;
}
@Override
public void run() {
while(isSotp){
try {
Thread.sleep(500);
rs.setText(getnumber(n) + "");
System.out.println("1232");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
处理事件类(响应button事件):
@Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o == start)
{
String number = num.getText();
try{
int n = Integer.parseInt(number);
isSotp = true;
thr t = new thr(rs, n);
t.start();
}catch(NumberFormatException e2){
System.err.println("格式错误");
num.setText("");
}
}else if(o == stop){
isSotp = false;
}
}
主程序启动:
public static void main(String[] args) { //主程序
number n = new number();
n.setResizable(false);
n.setTitle("学号点名小程序");
n.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
n.setSize(250, 200);
n.setVisible(true);
}
如果有看不懂上面的可以下载我放在网盘的代码示例,感谢您的阅读



