Brage Haavik February 2016

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. 

My goal is to make the randomly generated number appear along with when the frame is opened. As far as now, the randomly generated number will only appear if I press my enter key on the JTextField RandomNumber.So my question is how would I make the random number appear inside the textfield without having to press any keys on my keyboard. Thanks! And apologies for the novice-level question!

Answers


Eric G February 2016

If you want to have your random number appear at the start of execution, put it outside of the action listener. The action listener will only execute when an action is triggered (hitting enter, etc).

Also i would suggest to try renaming your variables and make the first letter start with a lowercase. You can see Java naming conventions for variables 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.

Post Status

Asked in February 2016
Viewed 1,709 times
Voted 9
Answered 1 times

Search




Leave an answer