如何在java swing中触发keyReleased事件

时间:2014-04-02 06:51:53

标签: java swing events keylistener jtextcomponent

我试图在java swing中触发key release事件。

txtEmailId.addKeyListener(new KeyAdapter() {
            // override keyReleased listener on the Email TextField
            @Override
            public void keyReleased(KeyEvent e) {

                                System.out.println("ok");
            }
        });

以上代码现在成功运行我想在txtEmailId.setText("hello");之后手动调用此keyReleased事件如何实现?

1 个答案:

答案 0 :(得分:2)

而不是KeyAdapter使用DocumentListener。试试下一个例子:

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

public class TestFrame extends JFrame{

    public TestFrame(){
        init();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    private void init() {
        JTextField f = new JTextField();
        f.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent e) {
                validate(e);
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                validate(e);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                validate(e);
            }

            private void validate(DocumentEvent e) {
                try {
                    String text = e.getDocument().getText(0, e.getDocument().getLength());
                    if(text.equals("hello")){
                        System.out.println("ok");
                    }
                } catch (BadLocationException e1) {
                    e1.printStackTrace();
                }
            }
        });
        f.setText("hello");
        add(f);
    }

    public static void main(String... s){
        new TestFrame();
    }

}