如何让我的随机数立即出现在我的画面上?

时间:2016-02-08 20:10:23

标签: java swing netbeans jtextfield

JTextField RandomNumber = new JTextField(30);
//Code for randum number below.
gbc.gridx = 3;
gbc.gridy = 1;
RandomNumber.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {                       

    //Code for function goes here.  
    Random rn = new Random();
    RandomNumber.setText(Integer.toString(rn.nextInt(51))); 


    }}); 
p2.add(RandomNumber, gbc); //Adding to the panel, after done with all functions. 

我的目标是随机生成的数字与框架打开时一起显示。到目前为止,只有当我按下JTextField RandomNumber上的回车键时才会出现随机生成的数字。所以我的问题是如何在文本字段内显示随机数,而不必按键盘上的任何键。谢谢!并为新手级别的问题道歉!

1 个答案:

答案 0 :(得分:1)

如果要在执行开始时显示随机数,请将其置于动作侦听器之外。当动作被触发时,动作监听器将执行(按下输入等)。

另外我建议尝试重命名变量并使第一个字母以小写字母开头。您可以看到变量Here

的Java命名约定
JTextField randomNumberTextField= new JTextField(30);
//Code for randum number below.
gbc.gridx = 3;
gbc.gridy = 1;
randomNumberTextField.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {                      

           // Code to execute when you hit enter


    }}); 

//Code for function goes here.  
Random rn = new Random();
randomNumberTextField.setText(Integer.toString(rn.nextInt(51)));
p2.add(randomNumberTextField, gbc); //Adding to the panel, after done with all functions.