Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-MVC-右键单击Jbutton_Java_Model View Controller - Fatal编程技术网

Java-MVC-右键单击Jbutton

Java-MVC-右键单击Jbutton,java,model-view-controller,Java,Model View Controller,我尝试将MVC与Jbuttons结合使用,并检查是否用鼠标左键或右键单击按下了按钮,这让我感到很受挫 当我必须处理单个(左)点时,我使用的方法如下: MyView extends JFrame{ JButton[] mybuttons; public MyView(){ //init mybuttons with a proper setActionCommand("button_name") } public void setActionL

我尝试将MVC与Jbuttons结合使用,并检查是否用鼠标左键或右键单击按下了按钮,这让我感到很受挫

当我必须处理单个(左)点时,我使用的方法如下:

MyView extends JFrame{

    JButton[] mybuttons;

    public MyView(){
        //init mybuttons with a proper setActionCommand("button_name")
    }

    public void setActionListener(ActionListener al) {
        for(JButton button:mybuttons){
            button.addActionListener(al);
        }
    }
}

MyController {
    MyModel mymodel;
    MyView myview;

    public MyController(MyModel mymodel,MyView myview){
        this.mymodel=mymodel;
        this.myview=myview;
        this.myview.setActionListener(new MyControllerActionListener());
    }

    public class MyControllerActionListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent ae){
            String command = ae.getActionCommand();
            switch (command){
                case "Button0":
                    ...
                    break;
                case "Button1":
                    ...
                    break;
        }
}
现在我想对MouseAdapter使用相同的方法,所以我尝试了:

public class MyMouseControllerAdapter extends MouseAdapter {
    public void mouseClicked(MouseEvent e){

        if (e.getButton() == MouseEvent.BUTTON1) {
           System.out.println("Left click");
        }
        else if (e.getButton() == MouseEvent.BUTTON3) {
            System.out.println("Right click");
        }

    }
}

但是我找不到方法来检查按下的jbutton是什么

您可以获得
MouseEvent
的源代码,并查看它是哪个组件:

JButton source = (JButton )e.getSource();

if(source == mybuttons[0]){
  // do stuff
}
else if(source == mybuttons[1]){
  // do stuff
}
...