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上的回车键时才会出现随机生成的数字。所以我的问题是如何在文本字段内显示随机数,而不必按键盘上的任何键。谢谢!并为新手级别的问题道歉!
答案 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.