• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

java实现给你一个1~1000的随机数请你猜数字大小

java实例 海叔叔 4年前 (2021-10-11) 59次浏览 已收录 0个评论

本文由搞代码网为大家展示了java实现给你一个1~1000的随机数请你猜数字大小》的代码案例,请各位coder不吝赐教,也欢迎coder点赞收藏转发,感谢

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Chp13_2 extends JFrame {

	private JButton chongwan;
	private JTextField field;
	private JLabel label1, label2;
	private Container container;
	private int shuzi = (int) (Math.random() * 1000 + 1);

	Chp13_2() {
		super("猜数游戏");
		container = getContentPane();
		container.setLayout(new FlowLayout());
		label1 = new JLabel("给你一个1~1000的随机数请你猜,请输入你猜的数:");
		container.add(label1);
		field = new JTextField(20);
		field.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent arg0) {
			}
			public void keyReleased(KeyEvent arg0) {

				int shuru = Integer.parseInt(field.getText());
				if (shuru < shuzi) {
					container.setBackground(Color.BLUE);
					label2.setText("你猜小了!");
				} else if (shuru > shuzi) {
					container.setBackground(Color.RED);
					label2.setText("你猜大了!");
				} else if (shuru == shuzi) {
					container.setBackground(Color.WHITE);
					label2.setText("你猜对了!");
					field.setEditable(false);
				}
			}
			public void keyTyped(KeyEvent arg0) {
			}
		});
		container.add(field);
		label2 = new JLabel("  ");
		container.add(label2);
		chongwan = new JButton("重玩");
		chongwan.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				shuzi = (int) (Math.random() * 1000 + 1);
				field.setEditable(true);
			}
		});
		container.add(chongwan);
		setSize(500, 400);
		setVisible(true);
	}

	public static void main(String[] args) {
		Chp13_2 application = new Chp13_2();
		application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:java实现给你一个1~1000的随机数请你猜数字大小
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址