Java猜数字游戏图形界面代码

2020-05-30 游戏 53阅读
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Randow implements WindowListener {
Frame f = new Frame("猜数字游戏");
int i =0 ;
Label l1 = new Label("猜数字游戏,请先产生随机数:",Label.LEFT);
Label l2 = new Label("请输入您猜测的数(1—100的整数):",Label.LEFT);
Label l3 = new Label("反馈信息:",Label.LEFT);
TextField T1 = new TextField();
TextField T2 = new TextField();
Button a = new Button("产生随机数");
Button b = new Button("碰碰运气");
Button c = new Button("不玩了");
public Randow(){
//f.setLayout(new GridLayout(4,2));
f.setSize(300,400);
f.setLayout(null);
f.add(l1);
f.add(a);
f.add(l2);
f.add(T1);
f.add(b);
f.add(c);
f.add(l3);
f.add(T2);
l1.setBounds(20, 40, 200, 20);
l2.setBounds(20, 80, 200, 20);
l3.setBounds(20, 140, 200, 20);
T1.setBounds(250, 80, 100, 20);
T2.setBounds(250, 140, 180, 20);
a.setBounds(250, 40, 100, 20);
b.setBounds(20, 100, 100, 20);
c.setBounds(250, 100, 100, 20);

f.setVisible(true);
f.pack();
f.addWindowListener(this);//注册窗口监听器
T2.setEditable(false);

a.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
i = (int)(Math.random() * 100 ) + 1;
}
});
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(i <= 0){
T2.setText("请先单击“产生随机数字”按钮");
}else if( Integer.parseInt(T1.getText().trim())>=100){
T2.setText("请确定输入数字的准确性");
}else{
if(i < Integer.parseInt(T1.getText().trim())){
T2.setText("猜大了");
}else if(i == Integer.parseInt(T1.getText().trim())){
T2.setText("猜对了");
}else{
T2.setText("猜小了");
}
}
}
});
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
T1.setText("");
T2.setText("");
}
});
}
public static void main(String args[]){
new Randow();
}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {

}

public void windowClosing(WindowEvent e) {
System.exit(0);

}
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com