简体   繁体   中英

Java Swing JTextField text one tick behind

I use this Java code for demonstration (Just created using 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);
    }

}

and if you type anything into the textfield the label shows everything exactly except prior to the last Buttonpress. Is there any way to fix that? thank you!

The text field contents change only after the key listener is notified. Instead of trying to track key presses, it is better to listen to the changes in the contents of the text field. This ensures that you also catch changes made by other means, such as cut and paste. The interface for doing that is 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) {
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM