如何创建KeyEvent

时间:2013-02-14 02:51:47

标签: java jtextfield keylistener keyevent

当我创建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?,但是我不能让机器人工作;当按键被按下时没有任何反应。

4 个答案:

答案 0 :(得分:4)

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);

示例(dunno,如果这是正确的方式,但它产生正确的输出):

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)

答案 1 :(得分:2)

使用robot时,首先获取将KeyListener添加到的组件的焦点。然后你可以使用机器人来模拟按键。作为替代方法,您可以在添加侦听器的组件上使用dispatchEvent。

KeyEvent key = new KeyEvent(inputField, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'Z');
inputField.dispatchEvent(key);

为您提供:

JInputField InputField = new JInputField();

您也可以创建如上所述的KeyEvent并将其传递给侦听器的keyTyped方法。 至于keyPrssed,你也可以这样做。

答案 2 :(得分:1)

你说:

  

我相信这会让我的代码更有效率。当满足某些条件时(我正在做挂人,这是一个与我的老师开玩笑的“作弊”),计算机将按正确的键来“猜测”答案。然后有简单的,我想知道我能不能?一部分。当我看到JButton.doClick()并且想知道它是否有一个JTextFields

时就开始了

正如我所怀疑的,你这一切都是错的。如果您希望程序为您按键,则无需创建KeyEvent。如果“键”是JButton,那么只需在按钮上调用doClick()即可。如果您希望将文本填充到JTextField中,那么只需设置文本就可以了。即,

例如,如果您在Swing Timer中调用下面的文本位(为了减慢速度,以便您看到正在添加的文本:

String myText = myTextField.getText();
myText += nextBitOfText;
myTextField.setText(myText);

你可能会得到你想要的效果。

例如:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;

@SuppressWarnings("serial")
public class AddTextToTextField extends JPanel {
   public static final String[] POSSIBLE_TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
   public static final int TIMER_DELAY = 500;
   private JTextField myTextField = new JTextField(20);
   private JButton myButton = new JButton(new BtnAction("Press Me"));
   private Random random = new Random();

   public AddTextToTextField() {
      add(myTextField);
      add(myButton);
   }

   private class BtnAction extends AbstractAction {
      public BtnAction(String text) {
         super(text);
      }

      @Override
      public void actionPerformed(ActionEvent arg0) {
         setEnabled(false);
         myTextField.setText("");
         myTextField.setFocusable(false);
         String randomText = POSSIBLE_TEXTS[random.nextInt(POSSIBLE_TEXTS.length)];
         new Timer(TIMER_DELAY, new TimerAction(this, randomText)).start();
      }
   }

   private class TimerAction implements ActionListener {
      private AbstractAction btnAction;
      private String text;
      private int count = 0;

      public TimerAction(AbstractAction btnAction, String text) {
         this.btnAction = btnAction;
         this.text = text;
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         if (count <= text.length()) {
            myTextField.setText(text.substring(0, count));
            count++;
         } else {
            ((Timer)e.getSource()).stop();
            btnAction.setEnabled(true);
            myTextField.setFocusable(true);
         }
      }
   }

   private static void createAndShowGui() {
      AddTextToTextField mainPanel = new AddTextToTextField();

      JFrame frame = new JFrame("AddTextToTextField");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

答案 3 :(得分:0)

您可以使用它来发送虚拟事件:

textArea.dispatchEvent(new KeyEvent(jFrame,
        KeyEvent.KEY_TYPED, System.currentTimeMillis(),
        0,
        KeyEvent.VK_ENTER));

尝试一下,它应该可以工作,但那是来自内存