3

When i create the KeyListener, it requires the following fields:

public void keyPressed(KeyEvent e) 
{

}
public void keyReleased(KeyEvent e) 
{

}
public void keyTyped(KeyEvent e) 
{

}

When i put System.out.println(e) into the keyPressed method, though, it returns this when i press the enter key:

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]

This is obviously not a KeyEvent, so I cannot use it to call the keyPressed(KeyEvent e). What I want to be able to do is simulate the pressing of a key, specifically the enter key, in a way that would activate the keyListener and would output that text into a JTextArea.

Note: I looked at the accepted answer for How can I perfectly simulate KeyEvents?, and understood little of how it actually works, and i want code i understand. I also looked here How to simulate keyboard presses in java?, but not i could not get the robot to work; nothing happened when a key was supposed to be pressed.

4

4 回答 4

5

e 是按键事件。

如果你想查看 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)
于 2013-02-14T02:56:19.700 回答
2

使用机器人时,首先获取要添加 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,你也可以这样做。

于 2013-02-14T03:23:14.197 回答
1

You state:

I believe it would make part of my code more efficient. When certain conditions are met (I am doing hang man, and this is a "cheat" that is a joke with my teacher) the computer will press the correct keys to "guess" the answer. and then there is the simple, i wonder if i can? part of it. that got started when i saw JButton.doClick() and wondered if it had one for JTextFields

As I suspected, you are going about this all wrong. If you want your program to press keys for you, there's no need to create KeyEvents. If the "keys" are JButtons, then simply calling doClick() on the button will do. If you are desiring to fill text into a JTextField, then simply setting the text is all that is needed. i.e.,

For instance if you called the bit of text below in a Swing Timer (to slow it down so that you see the text being added:

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

You would likely get the effect you desire.

For example:

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();
         }
      });
   }
}
于 2013-02-14T03:19:24.867 回答
0

您可以使用它来调度虚拟事件:

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

试试看,应该可以,但那是凭记忆的

于 2013-02-14T02:58:23.270 回答