0

I have a problem with the following code. I created a dice program and I created some radio buttons. I want the radio buttons to do the following: When selected, I want to roll the dice the number that the button has; the problem is that once I click on it, it gives me the results. I want to select it and then click the roll button then give me the results.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
    Random dice = new Random ();
    int number; 
    for (int counter=1; counter<=5;counter++) {
        number= 1+dice.nextInt(6);
        JOptionPane.showMessageDialog(null, number);
    }
}                                        

private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Random dice = new Random ();
    int number = 0; 
    for (int counter=1; counter<=5;counter++) 
        number= 4+dice.nextInt(4);
    JOptionPane.showMessageDialog(null, number);
}
Jason C
  • 38,729
  • 14
  • 126
  • 182

2 Answers2

1
  • Create a roll button.

  • Add an ActionListener to the button.

  • In the ActionListener you fetch the selected value from the radiobuttons and roll the "dice".

You do not need any listener on the radiobuttons for this.

Xabster
  • 3,710
  • 15
  • 21
0

I'm not quite clear on your issue because you have not posted enough code.

However, if you want one button to do something and another button to show the results, you'll want to store your results somewhere when the first button is pressed, then display those stored results when the second button is pressed.

You should take your results, whatever they are (e.g. the value of the roll) and store them in, say, a field in the class. Then when you are ready to display the results, you can show the value of that field. Right now all of your work is being done in local variables in your methods, once those methods return the information is lost.

Hope that helps.

Jason C
  • 38,729
  • 14
  • 126
  • 182