Java Swing JTextField文本背后嘀嗒一声

时间:2015-02-28 18:12:58

标签: java swing delay jtextfield

我使用这个Java代码进行演示(刚刚使用eclipse创建)

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class executor extends JFrame {

    private JPanel contentPane;
    private JTextField textField;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    executor frame = new executor();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public executor() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        final JLabel lblNewLabel = new JLabel("New label");
        contentPane.add(lblNewLabel, BorderLayout.NORTH);

        textField = new JTextField();
        textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                lblNewLabel.setText(textField.getText());
            }
        });
        contentPane.add(textField, BorderLayout.CENTER);
        textField.setColumns(10);
    }

}

如果您在文本字段中键入任何内容,则标签会显示除最后一个之外的所有内容 Buttonpress。有没有办法解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:3)

文本字段内容仅在通知密钥侦听器后才会更改。而不是试图跟踪按键,最好是听取文本字段的内容中的更改。这可以确保您还可以捕获通过其他方式进行的更改,例如剪切和粘贴。这样做的界面是DocumentListener

textField.getDocument().addDocumentListener(new DocumentListener() {
    @Override
    public void removeUpdate(DocumentEvent e) {
        lblNewLabel.setText(textField.getText());
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        lblNewLabel.setText(textField.getText());
    }

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