编写一个猜数程序,该程序随机在1到1000的范围中选择一个供用户猜测的整数。界面上提供一个文本框来接收用户输入的猜测的数,如果用户猜得太大,则背景变为红色,如果猜得太小,背景变为蓝色。用户猜对后,文本框变为不可编辑,同时提示用户猜对了。界面上提供一个按钮,使用户可以重新开始这个游戏。在界面上还需显示用户猜测的次数。示例输出如图所示。
实验步骤:
(1) 定义继承自JFrame的类,在该类中添加界面各部分;
(2) 定义事件监听器类完成事件处理;
(3) 定义一个包含main方法的测试类,在该类中创建框架类对象,并显示。
实验提示:
(1) 使用面板进行页面布局;
(2) 可以使用内部类定义事件监听器类;
(3) 按钮点击通过处理ActionEvent事件来完成响应。
代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
class Gs extends JPanel implements ActionListener{
private int cnt;
private int truenb;
private JPanel all;
private JLabel lb1,lb2,lb3,lb4;
private JButton bnt1,bnt2,bnt3;
private JTextField inp;
private JFrame jf;
public void generate(){
//生成随机数作为答案
Random r=new Random();
truenb=r.nextInt(1000)+1;
}
public Gs(){
cnt=0;
generate();
//生成所有物件的容器
all=new JPanel();
all.setLayout(null); //自己布局..
// all.setBounds(100,80,500,320);
// JLabel提示信息
lb1= new JLabel("您已经猜了"+cnt+"次");
lb1.setBounds(5, 5, 150, 20);
lb1.setFont(new Font("宋体",Font.BOLD,18));
// lb1.setVisible(true);
all.add(lb1);
lb2=new JLabel();
lb2.setText("输入猜测的数");
lb2.setFont(new Font("宋体",Font.BOLD,16));
lb2.setBounds(5, 60, 100, 20);
all.add(lb2);
inp=new JTextField();
inp.setBounds(106, 60, 100, 20);
inp.setBackground(Color.GREEN);
all.add(inp);
lb3=new JLabel();
lb3.setFont(new Font("宋体",Font.BOLD,16));
lb3.setBounds(235, 60, 120, 20);
lb3.setVisible(false);
all.add(lb3);
lb4=new JLabel("恭喜你猜对了");
lb4.setFont(new Font("宋体",Font.BOLD,16));
lb4.setBounds(10, 150, 120, 20);
lb4.setVisible(false);
all.add(lb4);
bnt1=new JButton("确定");
bnt1.setBounds(5, 90, 60, 30);
all.add(bnt1);
bnt2=new JButton("重新开始");
bnt2.setBounds(75, 90, 90, 30);
all.add(bnt2);
bnt3=new JButton("退出");
bnt3.setBounds(175, 90, 60, 30);
all.add(bnt3);
//给按钮添加事件监听
bnt1.addActionListener(this); //传this指针方便判断
bnt2.addActionListener(this);
bnt3.addActionListener(this);
//将Jpanel加入jframe
jf=new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setTitle("猜数游戏");
// jf.setLayout(null);
jf.setBounds(250,200,450,350);
jf.add(all);
jf.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==bnt1){ //确定按钮
cnt++;
lb1.setText("您已经猜了"+cnt+"次");
int gus=Integer.valueOf(inp.getText());
if(gus<truenb){ //太小
lb3.setVisible(true);
lb3.setText("猜测的数太小!");
all.setBackground(Color.BLUE);
}
else if(gus>truenb){ //太大
lb3.setVisible(true);
lb3.setText("猜测的数太大!");
all.setBackground(Color.RED);
}
else{ //猜对了
lb4.setVisible(true);
inp.setEditable(false); //禁止用户编辑
bnt1.setEnabled(false); //禁止按确认按钮
lb3.setVisible(false);
all.setBackground(Color.GREEN);
}
}
else if(e.getSource()==bnt2) //重开
{
cnt=0; //重开次数置零
lb1.setText("您已经猜了"+cnt+"次");
generate(); //生成新数
all.setBackground(null); //清除背景色
inp.setText(null); //清空输入框
inp.setEditable(true);
lb4.setVisible(false); //胜利提示关掉
bnt1.setEnabled(true); //允许按确认按钮
lb3.setVisible(false);
}
else { //退出
System.exit(0);
}
}
}
public class Main {
public static void main(String[] args) {
new Gs();
}
}