您的位置:首页 > 编程语言 > Java开发

《Java 编程技巧1001条》第417条: 检测多个修饰键

2017-12-25 09:08 357 查看



《Java 编程技巧1001条》第11章 事件驱动 第417条 检测多个修饰键 
417 Detecting Multiple Modifier Keys
417 检测多重变动键
In Tip 414, you learned that Java supports three types of keyboard characters. The first type are normal keys, which you learned to handle in the previous two tips. Another type of keys are the modifier keys. In Tip 415, you learned how to detect if the user has pressed a modifier key during a mouse click. Now, you will learn how to detect if multiple modifier keys were pressed at the same time.
在TIP 414中,你已知道了Java支持三种类型的键盘字符. 第一种类型是正常的键,这一种类型你已在前两个TIP中学过了. 另一种类型的键是修饰键,TIP 415中你已学过了怎样检测用户在击mouse键时按下了一个修饰键. 现在,你将学到怎样检测用户是否同时按下多个修饰键.
The Event class modifiers variable is a bit field that lets a variable contain multiple flags. Within the modifiers variable, Java sets one bit for each of the Shift, Ctrl, and Alt keys. Within your program, you can test which modifiers are set by performing a bitwise AND operation of the modifier constant and the modifiers variable. The following program, multipleModifier.java, demonstrates how to detect the Shift and Ctrl modifier keys when a normal key has been pressed:
Event类的modifiers(修饰键)变量是一个bit域,这样在一个变量中可容纳多个标记.在modifiers变量中,Java为Shift, Ctrl 和 Alt三个键分别设置一个bit. 在你的程序中,你可以对modifiers变量和modifiers常量实行按位乘(AND)操作,来检侧哪一个modifiers(修饰键)被设置了. 以下的程序multipleModifier.java说明怎样来检测用户在按正常键的同时也按下了Shift和Ctrl修饰键:

import java.applet.*;
import java.awt.*;

public class mutitipleModifier extends Applet {

    public void init()
      {
        resize(400, 300);
      }

    public boolean keyDown(Event evt, int key)
      {
        if (((evt.modifiers & Event.SHIFT_MASK) > 0) &&
           ((evt.modifiers & Event.CTRL_MASK) > 0))
          System.out.println("SHIFT and CTRL pressed");

        return(true);
      }
  }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: