Question

For the life of me I cannot find any help with this on the internet. My goal is to write a function that happens when shift is held and a mouse is clicked on the application. Right now I am just focusing on shift.

I have this class:

public void keyPressed(KeyEvent e)
{

    if (e.isShiftDown())
    {
        //Do Something
    }

}

Then in my main class I guessed at what I thought might work and it failed.

KeyEvent e = new KeyEvent;
keyPressed(e);

With this error:

KeyEvent cannot be resolved to a variable

I have seen examples that have this very line of code. So I'm stuck. My knowledge of Java is too limited for me to have any ideas.

Any help is appreciated.

Was it helpful?

Solution

You may want to focus only on the click, as that is the defining event. Shift is a modifier key. When you have your MouseEvent me, do me.isShiftDown()

http://docs.oracle.com/javase/6/docs/api/java/awt/event/InputEvent.html

So I guess that would be something like

public void mousePressed(MouseEvent me) {
  if (me.isShiftDown()) {
    // Do the function
  }
}

Assuming you have some random object, for example a button, that can register clicks:

JButton button = new JButton("I'm a button!");
button.addMouseListener(new MouseListener() {
  public void mousePressed(MouseEvent me) {
    if (me.isShiftDown()) {
      // Do the function
    }
  }
});

Now, whenever the button is clicked, your program will automatically check to see if the shift key is pressed, and if so, execute your function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top