【问题标题】:how do i differentiate between two different JButtons in actionPerformed?我如何区分 actionPerformed 中的两个不同的 JButton?
【发布时间】:2013-06-13 04:35:50
【问题描述】:

所以我有我的 JButtons

public static JButton textYes = new JButton("Yes");
public static JButton textNo = new JButton("No");

我的菜单

public static String choiceReroll = "";
public static String menu = "";

还有我的 main() 方法

public static void main(String[] args) throws IOException {
    Greed gui = new Greed();
    gui.launchFrame();
    redirectSystemStreams();

    Container contentPane = f.getContentPane();
    contentPane.add(new Greed());

    Scanner is = new Scanner(System.in);
    System.out.println("Welcome to Greed...");
        do {
    System.out.println("Would you like to play? (yes/no)");
    menu = is.next();
            switch (menu) {
                case "yes":
                    jTextArea1.setText(null);
                    diceOne = 0;
                    diceTwo = 0;
                    diceThree = 0;
                    diceFour = 0;
                    diceFive = 0;
                    System.out.println("Rolling...");
                    Game();

                    break;
                case "no":
                    System.out.println("Goodbye...");
                    System.exit(0);

                    break;
                default:
                    invalidInput();

                    break;
            }
        } while (!"yes".equals(menu) || !"no".equals(menu));
}

然后我有我的 actionListeners

textYes.addActionListener(this);
textNo.addActionListener(this);

如何做到这一点,以便当我单击一个按钮或另一个按钮时,它会在menu = is.next();请求用户输入的地方输入文本

我还希望它只输入文本,具体取决于它单击的按钮。并让它输入文本,无论什么变量要求输入

例如:

menu = is.next();

对比

choiceReroll = is.next();

编辑:更多信息...

我也有我的 performAction() 方法

public void actionPerformed(ActionEvent e) {
    jTextArea1.setText(null);
    if (box1.isSelected()) {
        System.out.println("1 is selected");
        willRerollDiceOne = true;
    }
    else {
        System.out.println("1 not selected");
        willRerollDiceOne = false;
    }
    if (box2.isSelected()) {
        System.out.println("2 is selected");
        willRerollDiceTwo = true;
    }
    else {
        System.out.println("2 not selected");
        willRerollDiceTwo = false;
    }
    if (box3.isSelected()) {
        System.out.println("3 is selected");
        willRerollDiceThree = true;
    }
    else {
        System.out.println("3 not selected");
        willRerollDiceThree = false;
    }
    if (box4.isSelected()) {
        System.out.println("4 is selected");
        willRerollDiceFour = true;
    }
    else {
        System.out.println("4 not selected");
        willRerollDiceFour = false;
    }
    if (box5.isSelected()) {
        System.out.println("5 is selected");
        willRerollDiceFive = true;
    }
    else {
        System.out.println("5 not selected");
        willRerollDiceFive = false;
    }

编辑:我为按钮添加了 actionPerformed,但现在只显示一个

    if (area == "menu") {
        if(e.getSource() == textYes){
            menu = "yes";
        }
        if(e.getSource() == textNo){
            menu = "no";
        }
    }

但是当我点击按钮时,它没有更新,为什么? 我该如何解决这个问题?

编辑:在 if 语句中添加了“测试”打印输出

    if ("menu".equals(area)) {
            if(e.getSource() == textYes){
                menu = "yes";
                System.out.println("test");
            }
            if(e.getSource() == textNo){
                menu = "no";
            }

每次单击“是”按钮时都会打印“测试”

编辑:这是方法的其余部分:

    public static void main(String[] args) throws IOException {
        Greed gui = new Greed();
        gui.launchFrame();
        redirectSystemStreams();

        Container contentPane = f.getContentPane();
        contentPane.add(new Greed());

        Scanner is = new Scanner(System.in);
        System.out.println("Welcome to Greed...");
            do {
        System.out.println("Would you like to play? (yes/no)");
        area = "menu";
        menu = is.next();
                switch (menu) {
                    case "yes":
                        jTextArea1.setText(null);
                        diceOne = 0;
                        diceTwo = 0;
                        diceThree = 0;
                        diceFour = 0;
                        diceFive = 0;
                        System.out.println("Rolling...");
                        Game();

                        break;
                    case "no":
                        System.out.println("Goodbye...");
                        System.exit(0);

                        break;
                    default:
                        invalidInput();

                        break;
                }
            } while (!"yes".equals(menu) || !"no".equals(menu));
        area = "";
    }

    public static void Game() throws IOException {
        rollDiceOne();
        rollDiceTwo();
        rollDiceThree();
        rollDiceFour();
        rollDiceFive();

        //displayDice();
        displayDiceValues();
        f.validate();
        f.repaint();

        choiceRerollDice();
    }

    public static void choiceRerollDice() {
        Scanner is = new Scanner(System.in);
            do {
                if (!canRerollDiceOne && !canRerollDiceTwo && !canRerollDiceThree && !canRerollDiceFour && !canRerollDiceFive) {
                System.out.println("Sorry, but you may not reroll any more dice...");
                displayDiceValues();
                System.exit(0);
            }
            else {
        System.out.println("Would you like to reroll any (more) dice? (yes/no)");
            choiceReroll = is.next();
                switch (choiceReroll) {
                    case "yes":
                        rerollDice();
                        break;
                    case "no":
                        //endTurn();
                        displayDiceValues();
                        f.repaint();
                        //calculatePlayer1Score();
                        //System.out.println("Thank you for playing!");
                        //System.out.println("Goodbye!");
                        System.exit(0);
                    default:
                        invalidInput();
                    }
                }
            } while (!"yes".equals(choiceReroll) || !"no".equals(choiceReroll));
    }

    public static void rerollDice() {
        Scanner is = new Scanner(System.in);
        System.out.println("Which dice would you like to reroll? (Click the box under the dice!)");
        rollSel = is.next();
        switch (rollSel) {
            case "roll":
            if (willRerollDiceOne) {
                if (canRerollDiceOne) {
                    diceOne = 0;
                    rollDiceOne();
                    canRerollDiceOne = false;
                    box1.setEnabled(false);
                }
                else {
                    System.out.println("error");
                }
            }

            else {
            }
            if (willRerollDiceTwo) {
                if (canRerollDiceTwo) {
                diceTwo = 0;
                rollDiceTwo();
                canRerollDiceTwo = false;
                box2.setEnabled(false);
                }
                else {
                    System.out.println("error");
                }
            }
            else {
            }
            if (willRerollDiceThree) {
                if (canRerollDiceThree) {
                diceThree = 0;
                rollDiceThree();
                canRerollDiceThree = false;
                box3.setEnabled(false);
                }
            }
            else {
            }
            if (willRerollDiceFour) {
                if (canRerollDiceFour) {
                diceFour = 0;
                rollDiceFour();
                canRerollDiceFour = false;
                box4.setEnabled(false);
                }
            }
            else {
            }
            if (willRerollDiceFive) {
                if (canRerollDiceFive) {
                diceFive = 0;
                rollDiceFive();
                canRerollDiceFive = false;
                box5.setEnabled(false);
                }
            }
            else {
            }
            box1.setSelected(false);
            box2.setSelected(false);
            box3.setSelected(false);
            box4.setSelected(false);
            box5.setSelected(false);
            f.validate();
            f.repaint();
                break;
            default:
                System.out.println("Error...");
        }

【问题讨论】:

    标签: java swing user-interface jbutton actionlistener


    【解决方案1】:

    在您的 actionPerformed 方法中执行以下操作:

    public void actionPerformed(ActionEvent e) { 
        if(e.getSource() == textYes){
          //perform action when textYes clicked
        }
        if(e.getSource() == textNo){
          //perform action when textNo clicked
        }
    }
    

    而不是这个:

    Scanner is = new Scanner(System.in);
            System.out.println("Welcome to Greed...");
                do {
            System.out.println("Would you like to play? (yes/no)");
            area = "menu";
            menu = is.next();
                    switch (menu) {
                        case "yes":
                            jTextArea1.setText(null);
                            diceOne = 0;
                            diceTwo = 0;
                            diceThree = 0;
                            diceFour = 0;
                            diceFive = 0;
                            System.out.println("Rolling...");
                            Game();
    
                            break;
                        case "no":
                            System.out.println("Goodbye...");
                            System.exit(0);
    
                            break;
                        default:
                            invalidInput();
    
                            break;
                    }
                } while (!"yes".equals(menu) || !"no".equals(menu));
            area = "";
    

    您可以创建一个将输入作为参数的方法。

    public void start(String menu){
                    switch (menu) {
                        case "yes":
                            jTextArea1.setText(null);
                            diceOne = 0;
                            diceTwo = 0;
                            diceThree = 0;
                            diceFour = 0;
                            diceFive = 0;
                            System.out.println("Rolling...");
                            Game();
    
                            break;
                        case "no":
                            System.out.println("Goodbye...");
                            System.exit(0);
    
                            break;
                        default:
                            invalidInput();
    
                            break;
                    }
    }
    

    然后在执行的动作中,只做:

    if(e.getSource() == textYes){
                start("yes");
            }
            if(e.getSource() == textNo){
                start("no");
            }
    

    【讨论】:

    • 这有帮助!我还在底部添加了另一个编辑,如果你能检查一下,那就太棒了!谢谢大哥!
    • 不要将字符串与 == 进行比较。使用if(area.equals("menu"))
    • 好的,我修好了,但还是没有更新?我做错了什么?
    • 点击按钮时面积是否等于菜单?尝试在 if 语句之前打印区域。
    • 是的,确实如此。关于它为什么不更新的任何想法?
    【解决方案2】:

    如何区分 actionPerformed 中的两个不同 JButton? 我有我的 actionListeners

    textYes.addActionListener(this);
    textNo.addActionListener(this);
    

    最简洁的方法是使用单独的侦听器。您可以使用匿名内部类来执行此操作,例如

    textYes.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) { 
            // here you can do any necessary actions for the "Yes" button,
            // like calling a specific method of the outer class which handles the event
        }
    });
    
    textNo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) { 
            // here you can do any necessary actions for the "No" button,
            // like calling a specific method of the outer class which handles the event
        }
    });
    

    如果您仍想只使用一个动作侦听器,ActionEvent 中的getSource() 方法允许您访问事件源,正如@ZouZou 已经提到的那样。

    另见How do you add an ActionListener onto a JButton in Java

    【讨论】:

      【解决方案3】:

      ActionEvent,您可以获得action command。因此,只需 set an action command 到每个按钮即可识别它们。

      【讨论】:

        【解决方案4】:

        getSource() 由 EventObject 类指定,ActionEvent 是 (via java.awt.AWTEvent). 的子级,这为您提供了对事件来自的对象的引用

        或者使用setActionComman(String command)为每个JButton设置命令,然后使用getActionCommand获取相关操作命令。

        String cmd = event.getActionCommand();
        

        【讨论】:

          【解决方案5】:

          为每个字段分配不同的ActionListener。我强烈建议您这样做,并且不要使用ActionListener 扩展具有这些字段的容器并将其传递为this。它保留了封装性,它强制分离关注点,并且它是一个干净、易于理解的代码。

          所以,每个按钮都应该像这样添加ActionListener

          textYes.addActionListener(new ActionListener() {
              @Override
              public void actionPerformed(Action event e) {
                  //logic
              }
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-12-29
            • 1970-01-01
            • 2013-03-31
            • 2023-04-09
            • 1970-01-01
            • 1970-01-01
            • 2013-12-30
            相关资源
            最近更新 更多