One action listener, two JButtons

后端 未结 2 429
梦谈多话
梦谈多话 2021-01-03 02:21

I have two JButtons called \"Left\" and \"Right\". The \"Left\" button moves a rectangle object to the left and the \"Right\" button moves it to the right. I h

2条回答
  •  天命终不由人
    2021-01-03 02:29

    Set actionCommand to each of the button.

    // Set the action commands to both the buttons.

     btnOne.setActionCommand("1");
     btnTwo.setActionCommand("2");
    
    public void actionPerformed(ActionEvent e) {
     int action = Integer.parseInt(e.getActionCommand());
    
     switch(action) {
     case 1:
             //doSomething
             break;
     case 2: 
             // doSomething;
             break;
     }
    }
    

    UPDATE:

    public class JBtnExample {
        public static void main(String[] args) {
            JButton btnOne = new JButton();
            JButton btnTwo = new JButton();
    
            ActionClass actionEvent = new ActionClass();
    
            btnOne.addActionListener(actionEvent);
                    btnTwo.addActionListener(actionEvent);
    
            btnOne.setActionCommand("1");
            btnTwo.setActionCommand("2");
        }
    } 
    
    class ActionClass implements ActionListener {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            int action = Integer.parseInt(e.getActionCommand());
            switch (action) {
            case 1:
                // DOSomething
                break;
            case 2:
                // DOSomething
                break;                          
            default:
                break;
            }
        }
    }
    

提交回复
热议问题