功能:产生一个随机数,猜随机数的大小,机会只有3次,并且如果猜错了,焦点自动返回。
使用到的接口:ActionListener FocusListener;
代码:
package com.niit.guessgame; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; /** * */ /** * @author Annie * @date 2016年6月6日 * @description:猜数字游戏(用到了焦点事件,活动事件) */ public class GuessGame extends JFrame implements ActionListener,FocusListener{ public static void main(String[] args) { new GuessGame(); } JLabel hintLabel; JButton buttonGetNumber,buttonEnter; JTextField inputText; Random random; int number ; int count =1; int i =3; public GuessGame() { super("猜数字"); setLayout(new FlowLayout()); setSize(300, 300); buttonGetNumber = new JButton("得到一个随机数:"); hintLabel = new JLabel("输入你猜的数字",JLabel.CENTER); hintLabel.setBackground(Color.cyan); inputText = new JTextField(10); buttonEnter = new JButton("确定"); add(buttonGetNumber); add(hintLabel); add(inputText); add(buttonEnter); setVisible(true); buttonGetNumber.addActionListener(this); buttonEnter.addActionListener(this); inputText.addFocusListener(this); inputText.requestFocusInWindow(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); dispose(); } }); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == buttonGetNumber){ random = new Random(); number = random.nextInt(1000); hintLabel.setText("请输入你要猜的数字:"); }else if(e.getSource() == buttonEnter){ int guess = Integer.valueOf(inputText.getText()); if(number == guess){ hintLabel.setText("猜对了!"); }else if(number >guess){ count++; i--; hintLabel.setText("猜小了,你还有:"+i+"次机会,请继续输入"); inputText.requestFocusInWindow(); }else if (number < guess){ count++; i--; hintLabel.setText("猜大了,你还有:"+i+"次机会,请继续输入"); inputText.requestFocusInWindow();//获取焦点 } } if(count > 3){ JOptionPane.showConfirmDialog(getParent(), "game over"); } } @Override public void focusGained(FocusEvent e) { inputText = (JTextField) e.getSource(); inputText.setText(null); } @Override public void focusLost(FocusEvent e) { // TODO Auto-generated method stub } }
效果图: