猜数字游戏

package org.text.day01;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class HomeWork02 implements ActionListener {

    JTextField bText = new JTextField(20);

    JLabel foot = new JLabel("结果显示!");

    public void getMonder() {
        JFrame jf = new JFrame("HomeWork02");
        JPanel body = new JPanel(new FlowLayout());

        JLabel top = new JLabel("猜字游戏");

        JLabel bLabel = new JLabel("请输入1-100之间的整数:");
        JButton bBut = new JButton("开始");
        JButton bBut2 = new JButton("提交");
        bBut.addActionListener(this);
        bBut2.addActionListener(this);
        body.add(bLabel);
        body.add(bText);
        body.add(bBut);
        body.add(bBut2);

        jf.add(top, BorderLayout.NORTH);
        jf.add(body);
        jf.add(foot, BorderLayout.SOUTH);

        jf.setSize(400, 150);
        jf.setLocation(400, 500);
        jf.setVisible(true);
        jf.setResizable(false);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    int num;

    public void actionPerformed(ActionEvent e) {
        String comm = e.getActionCommand();
        if ("开始".equals(comm)) {
            Random ran = new Random();
            num = ran.nextInt(100) + 1;
            foot.setText("请输入要求的数!");
        } else {
            String str = bText.getText();
            if (str.matches("^\\d{1,3}$")) {
                int temp = Integer.parseInt(str);
                if (temp > num) {
                    foot.setText(temp + "猜大了");
                } else if (temp < num) {
                    foot.setText(temp + "猜小了");
                } else {
                    foot.setText("猜对了");
                    num = 0;
                }
            } else {
                foot.setText("格式输入错误!");
            }
            bText.setText("");
            bText.requestFocus();
        }
    }

    public static void main(String[] args) {
        HomeWork02 h = new HomeWork02();
        h.getMonder();
    }

}

你可能感兴趣的:(java,游戏,swing)