import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//导入相应的包
public class game {
public static int couBut = 0;
//创建一个公共整形coutBut用户控制输入次数
public static void main(String[] args) {
JFrame frame = new JFrame("猜数字游戏");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel userLabel = new JLabel("请输入一个100内整数进行试猜,注意允许竞猜的最大次数是5次!", SwingConstants.CENTER);
userLabel.setBounds(10,20,360,25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(160,50,80,25);
panel.add(userText);
userText.setHorizontalAlignment(JTextField.CENTER);
JButton loginButton = new JButton("确定");
loginButton.setBounds(160, 80, 80, 25);
panel.add(loginButton);
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
couBut += 1;
int guessnum;
guessnum = Integer.parseInt(userText.getText());
int realnumber = (int)(Math.random()*100+1);
if(couBut > 4 && couBut < 6){
userLabel.setText("您猜 5 次了都没猜对,这不怪你,程序就是这么扣!");
userText.setText("");
}
else if(couBut > 4){
System.exit(0);
}
else if(guessnum > realnumber){
userLabel.setText("您输入的数字太大了,请重新竞猜!");
userText.setText("");
}
else if(guessnum < realnumber){
userLabel.setText("您输入的数字太小了,请重新竞猜!");
userText.setText("");
}
else{
userLabel.se