JTextField文本的监听器更改

时间:2014-02-20 19:37:13

标签: java swing jtextfield focuslistener

我有一个JTextField,我想添加一个监听器,只要JTextField失去焦点(比如当我用鼠标按下另一个组件时)就会收到一些事件。此外,我希望听众在text JTextField jtextfield.setText(anotherText)参数更改时(例如,当我设置{{1}}时)接收事件。知道我该怎么办?

2 个答案:

答案 0 :(得分:6)

对于第一个,您需要FocusListener。对于第二个,您需要在文本字段的DocumentListener中添加document

答案 1 :(得分:2)

正如@MadProgrammer指出的那样,如果您只对监听text属性感兴趣。只需添加一个PropertyChangeListener。

示例:

   JTextField textfield = new JTextField();
   //for focus use FocusAdapter and just override focus lost
   textfield.addFocusListener(new FocusAdapter(){
       @Override
       public void focusLost(final FocusEvent evt){
           //i always like to wrap this method with swing utilities
           // which puts it at the end of the EventQueue, so it's executed after all pending events
           SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                    //code here
                }
           });
       } 
  });

  textfield.addPropertyChangeListener("text", new PropertyChangeListener(){
             @Override
             public void propertyChange(PropertyChangeEvent evt){
                    if(evt == null)
                        return;

                    if("text".equals(evt.getPropertyName())){
                         //code here
                    }
             }
  });