java图形界面版猜数游戏

王佳 2023-04-24 12:23:40
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class GuessNumGame{
    public static void main(String[] args){
        GuessNumGame guessNumGame = new GuessNumGame();
        guessNumGame.init();
    }
    JTextField text=new JTextField(20);
    JLabel label=new JLabel("请输入1-100之间数字!");

    Random a = new Random();
    int random = a.nextInt(101);
    public void init()
    {
        JFrame f=new JFrame();
        JPanel p=new JPanel();


        JButton btn=new JButton("我猜!");
        //创建内部类
        GuessListener guessListener = new GuessListener();
        //创建事件监听
        btn.addActionListener(guessListener);
        p.add(text);
        p.add(btn);
        p.add(label);

        f.add(p);

        f.setTitle("猜数字游戏");
        f.setSize(600, 600);
        f.setLocation(600, 200);
        f.setVisible(true);
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public class GuessListener implements ActionListener{

        public void actionPerformed(ActionEvent e) {
            //获取文本输入框内容
            String input=text.getText();
            //字符串转int
            int num=Integer.parseInt(input);
            System.out.print(random);
            //判断大小
            if(num<random)
                label.setText("猜小了!");
            else if(num>random)
                label.setText("猜大了!");
            else
                label.setText("猜对啦!");

        }
    }
}

...全文
92 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

50

社区成员

发帖
与我相关
我的任务
社区描述
产学研究,学术传承
社区管理员
  • 又菜又爱玩呜呜呜~
  • 两年半的个人练习生^_^
  • yolanda19910002
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧