1

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Kyle Wright
  • 520
  • 2
  • 9
  • 23

1 Answers1

3

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.

Russell Uhl
  • 4,181
  • 2
  • 18
  • 28
  • Okay, cool. But then in main how can I call the function? Or more specifically, how can I define a "MouseEvent" type? – Kyle Wright Jun 13 '13 at 20:48
  • @KyleWright When you attempt to write an event, you are attempting to programmatically create a click or a keypress, etc. It is far more common to want to CAPTURE (in your case) a click. I'll update my answer based on the assumption you want the latter behavior. – Russell Uhl Jun 13 '13 at 20:49
  • sure thing! Good luck with your program – Russell Uhl Jun 13 '13 at 20:58
  • @KyleWright: I forgot to mention: when you create the MouseListener, you have to include code to handle ALL of the mouse event types: mousePressed, mouseReleased, etc. (the code doesn't have to do anything, it just has to exist). Java will throw a fit if you don't. Having said that, look into using a MouseAdapter. It will let you create only the handlers you actually want. I don't know how to use them offhand, or I would have included them above. – Russell Uhl Jun 13 '13 at 21:01
  • @RussellUhl, using a MouseAdapter is the same as using a MouseListener, except you only need to implement the methods you want to override. The adapter provide empty implementations for all the methods. – camickr Jun 13 '13 at 21:10