Q:

java swing hold both mouse buttons

I want to implement a method where the user needs to hold the left and right mouse buttons at the same time.
I'm using Swing and Java 1.7.  I've tried this, but it doesn't detect the both-buttons case like I'd expect it to:
public void mousePressed(MouseEvent e) {    
     if (SwingUtilities.isLeftMouseButton(e) && SwingUtilities.isRightMouseButton(e)){
              ///code here
     }
}

i tried to separate methods and use bool values to decide if the mouse button is pressed and then i set a condition to find out if both of them are pressed at the same time , but that didint work out too ..

A:

This is an SSCCE that does what you want... i.e. if I understood your question correctly.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class StackOverflow15957076 extends MouseAdapter
{
    private JLabel status;

    private boolean isLeftPressed;
    private boolean isRightPressed;

    public StackOverflow15957076 ()
    {
        JFrame frame = new JFrame ();
        frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);

        JPanel panel = new JPanel (new FlowLayout (FlowLayout.CENTER));

        status = new JLabel ("waiting for both mouse buttons...");

        status.addMouseListener (this);

        panel.add (status);

        frame.add (panel);

        frame.pack ();
        frame.setVisible (true);

        isLeftPressed = false;
        isRightPressed = false;
    }

    @Override
    public void mousePressed (MouseEvent e)
    {
        if (SwingUtilities.isLeftMouseButton (e))
        {
            isLeftPressed = true;
        }
        else if (SwingUtilities.isRightMouseButton (e))
        {
            isRightPressed = true;
        }

        if (isLeftPressed && isRightPressed)
        {
            status.setText ("both buttons are pressed");
        }
    }

    @Override
    public void mouseReleased (MouseEvent e)
    {
        if (SwingUtilities.isLeftMouseButton (e))
        {
            isLeftPressed = false;
        }
        else if (SwingUtilities.isRightMouseButton (e))
        {
            isRightPressed = false;
        }

        status.setText ("waiting for both mouse buttons...");
    }

    public static void main (String[] args)
    {
        SwingUtilities.invokeLater (new Runnable ()
        {
            @Override
            public void run ()
            {
                new StackOverflow15957076 ();
            }
        });
    }
}

