猜数字游戏

 初学java写的第一个swing小程序 猜数字游戏
package com.newer.ui;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;

public class GuessNumber extends JFrame implements ActionListener{
	
	private JPanel bottonPanel;
	private JPanel middlePanel;
	private JPanel topPanel;
	
	private JLabel lblTitle;
	private JLabel lblMessage;
	
	private JTextField txtTitle;
	
	private JButton btnGuess;
	private JButton btnRestart;
	
	private Random ran;
	private int ranNumber;
	
	public GuessNumber(){
		Restarts();
		createRand();
		init();
		this.setVisible(true);
	}
	//产生随即数
	private void createRand(){
		if(ran == null){
			ran = new Random();
		}
		ranNumber = ran.nextInt(100)+1;
	}
	public void Restarts(){		
		createRand();
	}
	public void getNumber(){
		try{
		int number = Integer.parseInt(txtTitle.getText());
		
		String message="";
		if(number>ranNumber){
			message = "大了";
		
		}
		if(number<ranNumber){
			message = "小了";
		}
		if(number == ranNumber){
			message = "恭喜答对了";
		}
		
		lblMessage.setText(message);
		}catch(Exception e){
			JOptionPane.showMessageDialog(null, "请输入正确的数!");
		}
	}
	
	public void init(){
		
		this.setSize(400,300);
		this.setLocationRelativeTo(this);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle("猜 数 游 戏");
		this.setResizable(false);
		
		Container c=this.getContentPane();//设置面板
		c.setLayout(new BorderLayout());
		c.setBackground(Color.CYAN);
		
		//顶部面板
		topPanel = new JPanel();
		topPanel.setBackground(Color.CYAN);
		topPanel.setLayout(new FlowLayout());
		
		lblTitle = new JLabel("请输入你要猜的数:");
		txtTitle = new JTextField();
		txtTitle.setColumns(10);
		
		topPanel.add(lblTitle);
		topPanel.add(txtTitle);
		
		//设置中间面板
		middlePanel = new JPanel();
		middlePanel.setBackground(Color.CYAN);
		middlePanel.setLayout(new FlowLayout());
		
		lblMessage = new JLabel("提示");
		
		middlePanel.add(lblMessage);
		//设置底部面板
		bottonPanel = new JPanel();
		bottonPanel.setBackground(Color.CYAN);
		bottonPanel.setLayout(new FlowLayout());
		
		btnGuess = new JButton("猜测");
		btnGuess.addActionListener(this);//注册监听
		btnGuess.setActionCommand("guess");//设置暗号
		
		btnRestart = new JButton("重新开始");
		btnRestart.addActionListener(this);//注册监听
		btnRestart.setActionCommand("guessRestart");
		
		bottonPanel.add(btnGuess);
		bottonPanel.add(btnRestart);
		
		//把三个Panel面板加入主面板
		c.add(topPanel,BorderLayout.NORTH);
		c.add(middlePanel,BorderLayout.CENTER);
		c.add(bottonPanel,BorderLayout.SOUTH);		
	}
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
		//1.获取文本框的猜测数字
		//2、猜测数字和随机数比较,得到信息
		//3.将信息放到提示标签中
		//获得暗号
		if(e.getActionCommand().equals("guess")){
			getNumber();
		}	
		if(e.getActionCommand().equals("guessRestart")){
			txtTitle.setText("");
			lblMessage.setText("提示");
			Restarts();
		}
	}		
}

 

你可能感兴趣的:(游戏,C++,c,swing,C#)