本文实例为大家分享了java实现随机数生成器的具体代码,供大家参考,具体内容如下
自己编的随机数生成器,比较简陋,功能也单一,当作练手。
application.java
1
2
3
4
5
6
7
8
9
10
|
package src;
public class application {
public static void main(string[] args) {
windowboxlayout win= new windowboxlayout();
win.setbounds( 100 , 200 , 300 , 350 );
win.settitle( "随机数生成器" );
win.setvisible( true );
}
}
|
randomlistener.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package src;
import java.awt.event.actionevent;
import java.awt.event.actionlistener;
import java.util.random;
import javax.swing.*;
public class randomlistener implements actionlistener{
jtextfield text1;
jtextarea text2;
random random= new random();
int result= 0 ;
public void setjtextfield(jtextfield t){
text1=t;
}
public void setjtextarea(jtextarea t){
text2=t;
}
@override
public void actionperformed(actionevent e) {
try {
text2.settext( "" );
integer number=integer.parseint(text1.gettext());
result=random.nextint(number)+ 1 ;
text2.append(result+ "" );
}
catch (exception exp){
text2.append( "请输入数字字符" );
}
}
}
|
windowboxlayout.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
package src;
import javax.swing.*;
public class windowboxlayout extends jframe{
/**
*
*/
private static final long serialversionuid = 1l;
box basebox;
jtextfield text1;
jtextarea text2;
jbutton button;
randomlistener random;
public windowboxlayout(){
setlayout( new java.awt.flowlayout());
init();
setvisible( true );
setdefaultcloseoperation(jframe.exit_on_close);
}
void init(){
basebox=box.createverticalbox();
basebox.add( new jlabel( "请输入随机数的最大范围值:" ));
basebox.add(box.createverticalstrut( 8 ));
text1= new jtextfield( 5 );
basebox.add(text1);
basebox.add(box.createverticalstrut( 8 ));
button= new jbutton( "确定" );
basebox.add(box.createverticalstrut( 8 ));
basebox.add(button);
text2= new jtextarea( 6 , 12 );
basebox.add(box.createverticalstrut( 18 ));
basebox.add(text2);
add(basebox);
random= new randomlistener();
random.setjtextfield(text1);
random.setjtextarea(text2);
button.addactionlistener(random);
}
}
|
类结构图:
效果图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Coder__CS/article/details/51213996