在 Java 中轮流使用按钮

Taking turns with buttons in Java

我正在制作一个玩家轮流玩的游戏,每个玩家都有一组按钮,轮到他们时可以点击这些按钮。下面是一个示例代码,它遵循我所说的逻辑。但是当我点击 "btn1" 时,它会打印三个 1,我仍然可以点击第二个按钮。

 //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;
                }});

        }

我知道可能是什么问题,但我不知道该怎么办。

替换循环

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

只有

player1();
player2();

与其向按钮添加 3 次相同的侦听器,不如只添加一次

如果您只想启用和禁用按钮,为什么不这样做:

    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);
            }});

    }