0

I am trying to create a JButton that will know whether or not it was right or left clicked when it was pressed. Here is my action listener for the JButton

 buttons[i][j].addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e){ 
        JButton button=(JButton)e.getSource();
 StringTokenizer st=new StringTokenizer(button.getName());
      
        }
       });

And here is my code for the Mouse listener

 public void mouseClicked(MouseEvent event){
  
  if(event.getButton()==1)
  {
   startPosition.move(event.getX(),event.getY());
   System.out.println(startPosition.getLocation());
   System.out.println("row="+row+" column="+column);
   
  }
  else
  {
   endPosition.move(event.getX(),event.getY());
   System.out.println("row="+row+" column="+column);
   
  }
 }

I know how to tell whether or now the mouse was right or left clicked, but I can't figure out how to combine that with the action event of the button being pressed. Any help would be much appreciated. Thanks.

  • Also discussed in [addMouseListener or addActionListener or JButton?](http://stackoverflow.com/questions/3616761/addmouselistener-or-addactionlistener-or-jbutton) – argoc Apr 28 '16 at 01:11

1 Answers1

0

You can make a custom mouse listener class that will do this:

public class CustomMouseListener implements MouseListener {
    public void mouseClicked(MouseEvent e) {
        if (event.getButton() == MouseEvent.BUTTON1) { // left click
            // do stuff
        }
        if (event.getButton() == MouseEvent.BUTTON3) { //right click
            // do stuff
        }
    }

    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }
}    

In the class with your JButtons:

buttons[i][j].addMouseListener(new CustomMouseListener());
Santiago Benoit
  • 994
  • 1
  • 8
  • 22