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.

4

1 回答 1

3

您可能只想关注单击,因为这是定义事件。Shift 是修饰键。当你有你的 MouseEvent 我时,做me.isShiftDown()

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

所以我想这会像

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

假设您有一些可以注册点击的随机对象,例如一个按钮:

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

现在,每当单击按钮时,您的程序将自动检查是否按下了 shift 键,如果是,则执行您的函数。

于 2013-06-13T20:42:40.880 回答