package com.ali.Game;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
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;
/**
* 猜数字游戏
*
* @author 小小小v
* @date 2014年7月18
*/
public class GuessNumber extends JFrame implements ActionListener {
private static final long serialVersionUID = 1389459121259063627L;
private static Random rand = new Random();// 定义一个随机数产生器
private JPanel contentPanel = new JPanel();// 内容面板,用来放面板和标签
private JPanel controlPanel = new JPanel();// 底部按钮的控制面板
private JLabel lblBegin = new JLabel("开始数字");
private JLabel lblEnd = new JLabel("终止数字");
private JLabel lblInput = new JLabel("输入数字");
private JTextField txtBegin = new JTextField(10);
private JTextField txtEnd = new JTextField(10);
private JTextField txtInput = new JTextField(10);
private JButton btnStart = new JButton("开始!");
private JButton btnGuess = new JButton("猜猜猜");
private JButton btnExit = new JButton("退出!");
private int begin, end, r, input;// 分别表示开始数字 终止数字 随机数和输入数字
public GuessNumber(String title) {
super(title);
init();
this.setLocation(300, 200);
this.setSize(350, 400);
this.setResizable(false);// 窗口大小不可变
this.setVisible(true);
}
private void init() {
this.setLayout(new BorderLayout());
this.add(contentPanel, BorderLayout.CENTER);
this.add(controlPanel, BorderLayout.SOUTH);
controlPanel.setLayout(new FlowLayout());// 增加可读性
controlPanel.add(btnStart);//controlPanel 控制面板
controlPanel.add(btnGuess);
controlPanel.add(btnExit);
contentPanel.setLayout(new GridLayout(3, 2));//contentPanel 内容面板
contentPanel.add(lblBegin);
contentPanel.add(txtBegin);
contentPanel.add(lblEnd);
contentPanel.add(txtEnd);
contentPanel.add(lblInput);
contentPanel.add(txtInput);
/**
* 让btnStart,btnGuess,btnExit注册同一个按钮点击事件的监听器。当事件发生时, 系统将自动调用回调函数
* public viod actionPerformed(ActionEvent e);
*/
btnStart.addActionListener(this);
btnGuess.addActionListener(this);
btnExit.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
JButton obj = (JButton) e.getSource();// 获取事件源
if (obj == btnStart) {
/* 点击开始按钮的业务逻辑 */
begin = Integer.parseInt(txtBegin.getText());// 将一个字符串解析为int
end = Integer.parseInt(txtEnd.getText());
r = begin + rand.nextInt(end - begin);
} else if (obj == btnGuess) {
/* 点击猜数按钮的业务逻辑 */
input = Integer.parseInt(txtInput.getText());
if (r == input) {
System.out.println("Game Over");
} else if (input < r) {
begin = input + 1;
txtBegin.setText("" + begin);
} else {
end = input - 1;
txtEnd.setText("" + end);
}
} else {
/* 退出代码 */
}
}
public static void main(String[] args) {
GuessNumber window = new GuessNumber("你猜我猜大家猜");
}
}
------解决方案--------------------
System.exit(0);
------解决方案--------------------
楼上正解,结束Java虚拟机!