user1546716
user1546716

Reputation: 101

MouseListener and KeyListener used at the same time

How do I use MouseListener and KeyListener at the same time?

For example, how to do something like this

public void keyPressed( KeyEvent e){
// If the mouse button is clicked while any key is held down, print the key
}

Upvotes: 0

Views: 2060

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347194

You could try checking the state of the KeyEvent modifiers, for example...

addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        int mods = e.getModifiers();
        System.out.println(mods);
        if ((mods & KeyEvent.BUTTON1_MASK) != 0) {
            System.out.println("Button1 down");
        }
    }
});

I should also point out, you can do...

int ext = e.getModifiersEx();
if ((ext & KeyEvent.BUTTON1_DOWN_MASK) != 0) {
    System.out.println("Button1_down_mask");
}

Which, as I've just discovered, produces results for other mouse buttons...

Upvotes: 1

Joshua Hyatt
Joshua Hyatt

Reputation: 1330

Use a boolean value for whether a mouse button is held down, and then update that variable in a MouseListener.

boolean buttonDown = false;

public class ExampleListener implements MouseListener {
    public void mousePressed(MouseEvent e) {
        buttonDown = true;
    }

    public void mouseReleased(MouseEvent e) {
        buttonDown = false;
    }

    //Other implemented methods unimportant to this post... 
}

Then, in your KeyListener class, just test the buttonDown variable.

Upvotes: 2

PlasmaPower
PlasmaPower

Reputation: 1878

Try creating a boolean isKeyPressed. In keyPressed, set it to true and in keyReleased set it to false. Then, when the mouse is clicked, first check if isKeyPressed is true.

Upvotes: 1

Related Questions