title: Selecting buttons at random in java
body: <p>How can I randomly select a java button, I am trying to create a tic-tac-toe game where the user plays the cpu or another player.  I have it working fine for 2 players but am stuck on 1 player game, I dont know if it can be done but my idea is that I just randomly select a button for the cpu check to see if its been selected previously and then assign the appropiate  x or o to the selected  square .</p>
  
  <pre><code>public void buttonSelected(ActionEvent click) {
  
      Object source = click.getSource();
  
      // loop through to see which button has been selected
      if(onePlayer){ 
  
  
          // User Vs CPU
          /*if((turn % 2 == 0)){// CPU Turn
              int selected;
              do {
                  selected = new Random().nextInt(btnEmpty.length );
                  if (chosen[selected -1] == false){
                      chosen[selected -1] = true;
                  }
  
              }while (chosen[selected -1] == true);
  
              source =  Integer.valueOf(selected);
              for(int i=1; i&lt;= btnNotSelected.length; i++) {
                  if(source == btnNotSelected[i] &amp;&amp; turn &lt; 10) {
                      btnClicked = true; // user has selected a button
                      // Check which user selected button and insert appropriate x or y
                      btnNotSelected[i].setText("X");
                      btnNotSelected[i].setEnabled(false); // disable selected button
                      pnlPlayingField.requestFocus(); // highlight selected panel 
                  }   
              } 
  
          }
          else{ //User Turn
              for(int i=1; i&lt;=9; i++) {
                  if(source == btnNotSelected[i] &amp;&amp; turn &lt; 10) {
                      btnClicked = true; // user has selected a button
                      // Check which user selected button and insert O
                      btnNotSelected[i].setText("O");
                      btnNotSelected[i].setEnabled(false);
                      chosen[i] = true;// disable selected button
                      pnlPlayingField.requestFocus(); // highlight selected panel
                  }
              }
  
          }  */
          turn++;  
      }
  
      else if(twoPlayer){
          for(int i=1; i&lt;=9; i++) {
              if(source == btnNotSelected[i] &amp;&amp; turn &lt; 10) {
                  btnClicked = true; // user has selected a button
                  // Check which user selected button and insert appropriate x or y
                  if(turn % 2 == 0){
                      btnNotSelected[i].setText("X");
                  }
                  else{
                      btnNotSelected[i].setText("O");
                  }
                  btnNotSelected[i].setEnabled(false); // disable selected button
                  pnlPlayingField.requestFocus(); // highlight selected panel
                  turn++;
      }`
  </code></pre>