加班到现在,,,,苦逼的IT啊..
package com.sunyard.etp.ag.util.test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* 猜数游戏
*
@author Efy 2014-6-9 21:33:10
*
*/
public class GuestNum {
private int num;
private void init(){
//主窗体
JFrame mainFrame = new JFrame("猜数游戏");
//设置主窗体大小
mainFrame.setSize(200, 100);
//主窗体居中显示
mainFrame.setLocationRelativeTo(null);
//主窗体关闭时退出程序
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//主面板
JPanel mainPanel = new JPanel();
JButton start = new JButton("开始吧");
//各项组件按顺序添加
mainPanel.add(start);
mainFrame.add(mainPanel);
//为按钮注册监听
buttonListener(start);
//主窗体为可见(最后设置主窗体可见,否则组件未加载完成时,会不显示)
mainFrame.setVisible(true);
}
/**
* 开始按钮监听
*
@param button
*/
private void buttonListener(JButton button) {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//100以内随机
num = (int) (Math.random()*100);
//标记是否猜对了
boolean flag = false;
//没猜对继续猜,直到猜对
while(!flag){
String inputNum = JOptionPane.showInputDialog("请输入数字");
try {
if(Integer.parseInt(inputNum) == num){
JOptionPane.showMessageDialog(null, "恭喜你猜对了~");
flag = true;
}else if(Integer.parseInt(inputNum) < num){
JOptionPane.showMessageDialog(null, "魂淡,人家怎么可能那么小嘛~");
}else{
JOptionPane.showMessageDialog(null, "没猜对哦,人家没你想的那么大啦~");
}
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, "你输入的不是数字!");
}
}
}
});
}
/**
* @param args
*/
public static void main(String[] args) {
new GuestNum().init();
}
}