import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class guess extends JFrame implements ActionListener
{
JLabel title = new JLabel ("SAMPLE 1");
JTextField txt1 = new JTextField (10);
JLabel direction = new JLabel ("GUESS A NUMBER BETWEEN 1 AND 100");
JLabel status = new JLabel ();
JPanel pnl1 = new JPanel ();
JPanel pnl2 = new JPanel ();
JPanel pnl3 = new JPanel ();
public guess()
{
super ("guess the number");
Container c = getContentPane();
c.setLayout (new BorderLayout());
txt1.addActionListener(this);
pnl2.setLayout (new BorderLayout());
c.add(pnl1, BorderLayout.NORTH);
c.add(pnl2, BorderLayout.CENTER);
pnl1.add(title);
pnl2.add(direction, BorderLayout.NORTH);
pnl2.add(txt1, BorderLayout.CENTER);
pnl2.add(status, BorderLayout.SOUTH);
setVisible(true);
setSize(350,450);
}
public void guess(int i)
{
super ("guess the number");
Container c = getContentPane();
c.setLayout (new BorderLayout());
txt1.addActionListener(this);
pnl2.setLayout (new BorderLayout());
c.add(pnl1, BorderLayout.NORTH);
c.add(pnl2, BorderLayout.CENTER);
pnl1.add(title);
pnl2.add(direction, BorderLayout.NORTH);
pnl2.add(txt1, BorderLayout.CENTER);
pnl2.add(status, BorderLayout.SOUTH);
setVisible(true);
setSize(350,450);
}
public static void main(String args[])
{
guess start = new guess();
start.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
int counter = 1;
int num = (int)(Math.random() * 100);
if (e.getSource()==txt1)
{
int a = Integer.parseInt(txt1.getText());
while(a != num)
{
if(a < num)
int x = num - 10;
if(a >= x)
{
}
}
}
}
}
这是我的代码,但我的问题在于actionPerformed,我不知道何时放int num = (int)(Math.random() * 100);
因为如果我将它放在if(e.getSource)
之外那么它将始终生成一个随机数我想,但如果在我的新问题中,如果我重置为我的猜测输入一个新值,那么int num = (int)(Math.random() * 100);
会得到一个新值吗?
答案 0 :(得分:0)
您应该添加一个开始按钮,并默认禁用输入文本字段
单击开始按钮时,输入文本字段可以启用,并为该轮游戏生成随机数。
您还可以在游戏进行时禁用开始按钮
您可能希望限制猜测次数,之后玩家将失去游戏,启用开始按钮并禁用输入文本字段,直到新游戏开始。