【问题标题】:Does clicking on a JTextField call the actionPerformed method单击 JTextField 是否调用 actionPerformed 方法
【发布时间】:2014-05-28 05:54:21
【问题描述】:

我有多个JTextFields,我想看看在程序中选择了哪一个。目前看来,点击JTextField 似乎不会调用ActionEvent(您是这样说的吗?)。

public void actionPerformed(ActionEvent ae){
    if(e.getSource().equals(JTextField.class)){
        current = (JTextField) e.getSource();
        System.out.println(current);
    }
}

【问题讨论】:

    标签: java swing jframe jtextfield


    【解决方案1】:

    ActionListener 通常会在用户“操作”该字段时触发,对于大多数平台/外观来说,这是由用户按下 Enter 键触发的。

    我想你要的是FocusListener

    查看How to Write a Focus Listener了解更多详情

    如果您只想找出当前关注的组件,您可以使用KeyboardFocusManager

    Component focusedComponent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
    

    【讨论】:

    • 谢谢!这个很简单直接
    【解决方案2】:

    使用也可以使用addMouseListener

    jtextField.addMouseListener(new MouseAdapter(){
        public void mouseClicked(MouseEvent e){
            ...
        }
        public void mousePressed(MouseEvent e) {
    
        }
    
        public void mouseReleased(MouseEvent e) {
    
        }
    
        public void mouseEntered(MouseEvent e) {
    
        }
    
        public void mouseExited(MouseEvent e) {
    
        }
    
        });
    

    【讨论】:

      【解决方案3】:

      您是否将 actionListener 添加到 JTextFiled 中?

      JTextField tf= new JTextfield();
      tf.addActionListener(//class name goes there, if the actionListener is in a different class otherwise just say "this");
      

      【讨论】:

      • 我这样做了。这不会调用 ActionEvent
      猜你喜欢
      • 2012-09-13
      • 2013-03-27
      • 2023-03-08
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      相关资源
      最近更新 更多