猜数字小游戏

给大家推荐个靠谱的公众号程序员探索之路,大家一起加油 

主类:

import java.awt.*;
public class 猜数字 {
	public static void main(String[] args) {
	 window win=new window();
	 win.setTitle("猜数字");
	 win.setBounds(100, 100, 300, 300);
	 Container c=win.getContentPane();
	 c.setBackground(Color.green);//设置背景颜色
	}

}


 

window类

import javax.swing.*;
import java.awt.*;
public class window extends JFrame{
	JButton button1,button2;
	JLabel b1;
	JTextField text;
    public window(){
    	init();
    	setVisible(true);
    	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    void init(){
    	setLayout(new FlowLayout());
    	button1=new JButton("(点击)得到一个随机数");
    	add(button1);
    	text =new JTextField(10);
    	b1=new JLabel("");
    	add(b1);
    	add(text);
    	button2=new JButton("确定");
    	add(button2);
    	action ac=new action();
    	ac.setJlabel(b1);
    	ac.settext(text);
    	button1.addActionListener(ac);
    	action2 a=new action2();
    	a.setabel(b1);
    	a.settext(text);
    	button2.addActionListener(a);
    }
}


 

action类

import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class action implements ActionListener{
  int num;
  JLabel abel;
  JTextField text;
  public void setJlabel(JLabel abel){
	  this.abel=abel;
  }
  public void settext(JTextField text){
	  this.text=text;
  }
  JButton b1=new JButton("(点击)得到一个随机数");
  JButton b2=new JButton("确定");
  public void actionPerformed(ActionEvent e) {
	  Random rd=new Random();
	   num=rd.nextInt(100)+1;
	   abel.setText("请输入你的猜测");
	   init();
  }
  int init(){
	 return num; 
  }
}


 

action2类

import java.awt.event.*;
import javax.swing.*;
public class action2 implements ActionListener{
	action a=new action();
	int num=a.init();
	JTextField text;
	JLabel abel;
	public void settext(JTextField text){
		this.text=text;
	}
	public void setabel(JLabel abel){
		this.abel=abel;
	}
	public void actionPerformed(ActionEvent e){ 
	int guess=0;
	   try{
		   guess=Integer.parseInt(text.getText());
		   if(guess==num){
			   abel.setText("猜对了!");
		   }
		   if(guess>num){
			   abel.setText("猜大了!");
			   text.setText(null);
		   }
		   if(guess<num){
			   abel.setText("猜小了!");
			   text.setText(null);
		   }
	   }
	   catch(NumberFormatException event){
		   abel.setText("请输入数字字符!");
		   text.setText(null);
	   }
   }
}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值