Using multiple JButtons with the same label in Java

前端 未结 3 379
温柔的废话
温柔的废话 2020-12-12 07:26

I have two buttons in my project that both have a \"+\" label. When the actionPerformed() method is called, it calls a specific method based on the label. How can I distigui

3条回答
  •  独厮守ぢ
    2020-12-12 07:53

    Instead of this,

    public void actionPerformed (ActionEvent event) {
            String command = event.getActionCommand();
            if (command.equals("+")) {
                calcLifePoints(command);
            }
            if (command.equals("-")) {
                calcLifePoints(command);
            }
            if (command.equals(" + ")) {
                calcLifePoints(command);
            }
            if (command.equals(" - ")) {
                calcLifePoints(command);
            }
    
        }
    

    Use like this,

    public void actionPerformed (ActionEvent event) {
            Object command = event.getSource();
            if (command.equals(keypadPlus1)) {
                calcLifePoints(event.getActionCommand());
            }
            if (command.equals(keypadMinus1)) {
                calcLifePoints(event.getActionCommand());
            }
            if (command.equals(keypadPlus2)) {
                calcLifePoints(event.getActionCommand());
            }
            if (command.equals(keypadMinus2)) {
                calcLifePoints(event.getActionCommand());
            }
    
        }
    

提交回复
热议问题