Java检查是否按下了控制键

Mik*_*ika 4 java swing

我有一个Java函数,我想测试控制键是否被按下.我怎样才能做到这一点?

编辑:我正在使用摇摆gui.

Chr*_*nar 10

使用"isControlDown()"布尔值:

public void keyPressed (KeyEvent e)
{
     System.out.println(e.isControlDown());
}
Run Code Online (Sandbox Code Playgroud)


Sco*_*Izu 5

仅当按下的唯一键是控制键时,以上代码才有效。如果他们有ctrl键,并且偶然地(也许)按下了其他按钮,则不会捕获。

您可以只检查ctrl键

// Are just the CTRL switches left on
if(evt.getModifiers() == InputEvent.CTRL_MASK) {
    System.out.println("just the control key is pressed);
}
Run Code Online (Sandbox Code Playgroud)

模拟按下的多个键时,可以使用或位运算符。要模拟同时按住向左按钮和Ctrl键,请寻找该内容。

// Turn on all leftButton and CTRL switches
int desiredKey = InputEvent.BUTTON1_MASK | InputEvent.CTRL_MASK;  
Run Code Online (Sandbox Code Playgroud)

检查ctrl键是否按下时,您可以这样做

// If we turn off all switches not belonging to CTRL, are all the CTRL switches left on
if((evt.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) {
    System.out.println("Control Key is pressed and perhaps other keys as well");
}
Run Code Online (Sandbox Code Playgroud)

您还可以检查是否同时按下了左按钮和Ctrl蒙版

// If we turn off all switches not belonging to leftButton or CTRL, are all the leftButton and CTRL switches left on
if((evt.getModifiers() & desiredKey) == desiredKey) {
    System.out.println("left button and control keys are pressed and perhaps others as well");
}
Run Code Online (Sandbox Code Playgroud)

假设您有:

A | B
Run Code Online (Sandbox Code Playgroud)

您应该这样想。一个控制面板上有一堆开关。B还有一个控制面板,上面有许多开关。“ | B”的工作是做必要的最少工作,以确保所有B的开关都打开。

假设您有:

A & B
Run Code Online (Sandbox Code Playgroud)

“&B”的工作是完成关闭不是B的所有开关所需的最少工作。


Cha*_*tin 2

这取决于几件事。

如果您将 Java 程序作为控制台程序(基于文本)运行,则必须测试接收到的字符程序中的适当位。

否则,您应该查看适当的 GUI 类的 InputEvents,例如http://docs.oracle.com/javase/6/docs/api/java/awt/event/InputEvent.html

看看本教程:http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html