当我创建 KeyListener
时,它需要以下字段:
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
当我将 System.out.println(e)
放入 keyPressed
方法时,当我按下回车键时它会返回:
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=10,keyText=?,keyChar=?,keyLocation=KEY_LOCATION_STANDARD,rawCode=0,primaryLevelUnicode=0,scancode=0] on javax.swing.JButton[,1,1,100x100,alignmentX=0.0,alignmentY=0.5,border=com.apple.laf.AquaButtonBorder$Dynamic@13b33a0e,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=2,bottom=0,right=2],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=HI,defaultCapable=true]
这显然不是KeyEvent,所以我不能用它来调用keyPressed(KeyEvent e)
。我想要做的是模拟一个键的按下,特别是输入键,以激活 keyListener
并将该文本输出到 JTextArea 的方式。
注意:我查看了 How can I perfectly simulate KeyEvents? 的已接受答案,并且对它的实际工作原理了解甚少,我想要我理解的代码。我也看过这里How to simulate keyboard presses in java? ,但不是我无法让机器人工作;应该按下某个键时什么也没发生。
最佳答案
e 是 KeyEvent。
如果你想看e值,那么你可以试试这个
System.out.println(e.getKeyChar());
创建 KeyEvent :
KeyEvent e = new KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation);
示例(不知道这是不是正确的方法,但它会产生正确的输出):
Button a = new Button("click");
KeyEvent e;
e = new KeyEvent(a, 1, 20, 1, 10, 'a');
System.out.println(""+e.getKeyChar());
System.out.println(""+e.getKeyCode());
这是所有类型的 KeyEvent 参数
java.awt.event.KeyEvent
@Deprecated public KeyEvent(Component source, int id, long when, int modifiers, int keyCode)
Deprecated. as of JDK1.1
===
java.awt.event.KeyEvent
public KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar)
Constructs a KeyEvent object.
Note that passing in an invalid id results in unspecified behavior. This method throws an IllegalArgumentException if source is null.
Parameters:
source - the Component that originated the event id - an integer identifying the type of event when - a long integer that specifies the time the event occurred modifiers - the modifier keys down during event (shift, ctrl, alt, meta) Either extended _DOWN_MASK or old _MASK modifiers should be used, but both models should not be mixed in one event. Use of the extended modifiers is preferred. keyCode - the integer code for an actual key, or VK_UNDEFINED (for a key-typed event) keyChar - the Unicode character generated by this event, or CHAR_UNDEFINED (for key-pressed and key-released events which do not map to a valid Unicode character)
Throws:
IllegalArgumentException - if id is KEY_TYPED and keyChar is CHAR_UNDEFINED; or if id is KEY_TYPED and keyCode is not VK_UNDEFINED IllegalArgumentException - if source is null
===
java.awt.event.KeyEvent
public KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation)
关于java - 如何创建按键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867040/