如何在GUI中生成随机数?

时间:2013-05-30 19:27:25

标签: java parsing user-interface random jpanel

我写了一个GUI程序来猜测1到200之间的随机数。当我运行它时,我无法正确执行它。我可以猜两次相同的数字,有时它会说“太低”,有时它会说“太高”。我必须要尝试一些我尝试过的故障,但我很遗憾为什么这不起作用。这是我的代码:

    import java.util.Random;


    public class GuessPanel extends javax.swing.JPanel {

       protected Random random;
       protected int x;
       protected int n;

    public GuessPanel() {
        initComponents();
    }


    @SuppressWarnings("unchecked")
    **Generated Code**                    

    private void guessButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
         random = new Random();
         String s = userField.getText();
         int i = 200;
         x = random.nextInt(i);

         n = Integer.parseInt(s);

         if (x == n) 
         {
             answerLabel.setText("You guessed right!!!");
         } 
         else if (x > n)
         {
             answerLabel.setText("Your guess is too low, guess again");
         }  
         else if (x < n)
         {
             answerLabel.setText("Your guess is too high, guess again");
         }
}                                           
// Variables declaration - do not modify                     
private javax.swing.JLabel answerLabel;
private javax.swing.JButton guessButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField userField;
// End of variables declaration                   

}

1 个答案:

答案 0 :(得分:7)

每次按下“guess”按钮时,您都会生成一个新的随机数。加载GUI时要么这样做一次,要么创建一个新按钮来重置游戏并将随机数生成代码放在那里。