我怎样才能让我的随机数立即出现在我的框架上?
How would I make my random number appear instantly on my frame?
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.So 上按下回车键时,随机生成的数字才会出现我的问题是如何让随机数出现在文本字段内,而不必按键盘上的任何键。谢谢!并为新手级问题道歉!
如果你想让你的随机数出现在执行开始时,把它放在动作侦听器之外。动作侦听器将仅在动作被触发时执行(点击回车等)。
此外,我建议尝试重命名您的变量并使第一个字母以小写字母开头。您可以看到 Java 变量的命名约定 Here
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.
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.So 上按下回车键时,随机生成的数字才会出现我的问题是如何让随机数出现在文本字段内,而不必按键盘上的任何键。谢谢!并为新手级问题道歉!
如果你想让你的随机数出现在执行开始时,把它放在动作侦听器之外。动作侦听器将仅在动作被触发时执行(点击回车等)。
此外,我建议尝试重命名您的变量并使第一个字母以小写字母开头。您可以看到 Java 变量的命名约定 Here
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.