首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jtextfield和keylistener

Jtextfield和keylistener
EN

Stack Overflow用户
提问于 2014-04-09 06:53:33
回答 2查看 3.5K关注 0票数 0

我有一个jtextfield ( jtextfield,jt),只要用户在其中输入"e" (例如,要在jtextfield中自动写入单词"Example" ),我就想在其中输入它。

我使用代码:

代码语言:javascript
复制
KeyListener keyListener = new KeyListener() {
    public void keyPressed(KeyEvent e) {
        jt.setText("Example");
    }
} 

但是当e被按下时,这就给了"Examplee"!有什么想法吗?非常感谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-09 07:01:51

不要在文本组件上使用KeyListener,有一个问题(未被通知,变异异常,当用户粘贴到字段中时未被通知),相反,您应该使用一个DocumentFilter

例如..。

代码语言:javascript
复制
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class TextFieldExample {

    public static void main(String[] args) {
        new TextFieldExample();
    }

    public TextFieldExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTextField field = new JTextField(20);
                ((AbstractDocument)field.getDocument()).setDocumentFilter(new ExampleExpandingDocumentFilter());

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(field);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ExampleExpandingDocumentFilter extends DocumentFilter {

        @Override
        public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
            System.out.println("I" + text);
            super.insertString(fb, offset, text, attr);
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            if ("e".equalsIgnoreCase(text)) {
                text = "example";
            }
            super.replace(fb, offset, length, text, attrs); 
        }

    }

}
票数 5
EN

Stack Overflow用户

发布于 2014-04-09 07:04:24

您可以将您的jt.setText("Example");移动到KeyListenerpublic void keyReleased(KeyEvent e)中。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22954961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档