0

我正在开发一个 Java 项目,需要一个按键来模拟对 JTextField 的单击。我正在寻找的是 JButton doClick() 方法的等效项。

我试图让按键“输入”执行与单击 JTextField 完全相同的功能。

不确定要提供哪些其他信息。提前致谢。

4

4 回答 4

2

好的,谢谢你的帮助。我想我并不清楚,但由于您的一些想法,我现在已经找到了一种使我的代码工作的方法。

我已经想过只创建一个由两个函数调用的私有方法,但是部分代码需要知道用户单击了哪个 JTextField。我发现了 .getFocusOwner(),它允许我使用 Focus(JTextField)引用当前项目。像这样的东西

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_ENTER) {
            Object which = JFrame.getFocusOwner();                
            if(which.getClass() == JTextField.class)
                foo(which);
         }
    }

    public void mouseClicked(MouseEvent e) {                
        Object which = e.getSource();
        if(which.getClass()== JTextField.class) {
            foo(which);
        }
    }

可能有更好的方法来做到这一点,但基本上我有一个 JTextFields 数组,当用户单击下一个 JTextField 时程序运行正常,但是当按下回车时我不知道如何调用刚刚输入的 JTextField所以我想模拟点击 JTextField (需要焦点)。我想我应该解释一下我的整个问题。

谢谢你。

于 2010-03-15T23:10:51.243 回答
2
public void simulateKey(KeyEvent e, Component c) {
   Field f = KeyEvent.class.getField("focusManagerIsDispatching");
   f.setAccessible(true);
   f.set(e, Boolean.TRUE);
   c.dispatchEvent(e);
}

将“Enter”发送到您的 JTextField。这是从这里偷来的。

于 2010-03-15T04:40:08.753 回答
1

如果您希望由于鼠标和按键而发生相同的事情,那么让两者都调用一个方法不是更有意义吗?也就是说,您有一个类似的方法fieldClicked,它同时被 theMouseListenerKeyListener. 这将更容易调试 - 更少的事件,这可能非常令人困惑 - 并且可能更具可读性。

于 2010-03-15T06:31:04.353 回答
0

What I want is when the user presses enter, it calls the same code as when they click anywhere in the frame

Still doesn't make sense to me.

When the user clicks any where on the frame a couple of things happen:

a) the text field loses focus

b) some other component gains focus

You could add an ActionListener to the text field. The ActionListener is invoked when the Enter key is pressed. But then how to you guess where on the frame to generate a mouse click? Seems like random logic to me.

于 2010-03-15T05:04:50.817 回答