如何在GUI中生成随机数?

use*_*625 0 java random user-interface parsing 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                   
Run Code Online (Sandbox Code Playgroud)

}

Bil*_*ard 7

每次按下"猜测"按钮时,您都会生成一个新的随机数.在加载GUI时执行一次,或者创建一个新按钮来重置游戏并将随机数生成代码放在那里.