Hello I have been stuck on how to make a button display a random number.this is where I am right now. I cant figure out where the random number generator code would go. If I put it before the ActionListener if will just post right beside the button instead of appearing when the button is pressed. It keeps giving me the error message
Error: Cannot refer to the non-final local variable num1 defined in an enclosing scope.
Please refer the below code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import java.util.Random;
public class myTest {
public static void main(String[] args) {
Random generator = new Random();
int num1;
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
num1 = generator.nextInt(101);
System.out.println("the random number is:" +num1);
JButton button1 = new JButton("Push Me!");
frame.add(panel);
panel.add(button1);
frame.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
num1 = generator.nextInt(101);
System.out.println("the random number is:" +num1);
}
});
}
}