用隨機數寫的猜數字游戲(鍵盤可以控制)

1
2 import java.awt.*;
3 import javax.swing.*;
4 import java.awt.event.*;
5 import java.applet.Applet;
6 import java.awt.Container;
7 import java.util.*;
8
9 //int a =(int)(Math.random()*(15-5))+5;
10
11 public class homework extends Canvas
12 {
13
14 private static JFrame window = new JFrame("homework");
15 private static TextField tf = new TextField(20);
16 static int a = (int)(Math.random()*(100-0))+0;
17 private static JLabel jlabel = new JLabel("猜的消息");
18 public static void main(String[] args)
19 {
20 try
21 {
22 Button bn1 = new Button("猜一猜");
23 Button bn2 = new Button("重新來一局");
24 Container container = window.getContentPane();
25 Toolkit thekit = window.getToolkit();
26 bn2.addActionListener(new ActionListener()
27 {
28 public void actionPerformed(ActionEvent e)
29 {
30 reseta();
31 jlabel.setText("猜的消息");
32 }
33 }
34 );
35 bn1.addActionListener(new ActionListener()
36 {
37 public void actionPerformed(ActionEvent e)
38 {
39
40 int b = Integer.parseInt(tf.getText());
41 if(a > b)
42 {
43 jlabel.setText("你猜的數小了");
44 }
45 else if(a < b )
46 {
47 jlabel.setText("你猜的數大了");
48 }
49 else
50 {
51 jlabel.setText("恭喜!!你猜對了,請重新來");
52 reseta();
53 }
54 }
55
56 }
57 );
58 tf.addKeyListener(new KeyAdapter()
59 {
60 public void keyReleased(KeyEvent e) //按鍵被按下的時候
61 {
62 if(e.getKeyCode()==KeyEvent.VK_ENTER)
63 {
64 int b = Integer.parseInt(tf.getText());
65 if(a > b)
66 {
67 jlabel.setText("你猜的數小了");
68 }
69 else if(a < b )
70 {
71 jlabel.setText("你猜的數大了");
72 }
73 else
74 {
75 jlabel.setText("恭喜!!你猜對了,請重新來");
76 reseta();
77 }
78 }
79 }
80
81 }
82 );
83 Dimension wndsize = thekit.getScreenSize();
84 window.setBounds(wndsize.width/4,wndsize.height/4,wndsize.width/2,wndsize.height/2);
85 container.setLayout(new FlowLayout());
86 container.add(tf);
87 container.add(bn1);
88 container.add(bn2);
89 container.add(jlabel);
90 window.setVisible(true);
91 }
92 catch(Exception e)
93 {
94 }
95 }
96 public static void reseta()
97 {
98 a = (int)(Math.random()*(100-0))+0;
99 }
100