简体   繁体   中英

Taking turns with buttons in Java

I'm making a game where the players are taking turns and they would have a set of buttons each that they can click when it is their turn. Below is a sample code that follows the logic of what I am saying. But what happens is when I clicked the "btn1", it prints three 1s and I can still click the second button.

 //this loop is in the main
        for(int i=0; i<3;i++){
            if(player==1){
               player1();
            }
           else if (player==2){
              player2();
           }
       }

    public void player1(){
            btn1.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent arg0) {
                    System.out.println("\n1");
                    player=2;
                }});

        }

        public void player2(){
            btn2.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent arg0) {
                    System.out.println("\n2");
                    player=1;
                }});

        }

I can see what could be the problem but I don't know what to do.

Replace the loop

for(int i=0; i<3;i++){
        if(player==1){
           player1();
        }
       else if (player==2){
          player2();
       }
   }

with just

player1();
player2();

Instead of adding 3 times the same listener to the button add it just once

If all you want to do is enable and disable buttons, why not do:

    public void player1(){
        btn1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("\n1");
                player=2;
                btn1.setEnabled(false);
                btn2.setEnabled(true);
            }});

    }

    public void player2(){
        btn2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("\n2");       
                player=1;
                btn1.setEnabled(true);
                btn2.setEnabled(false);
            }});

    }       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM