gpt4 book ai didi

Java Swing JTextField 文本落后一格

转载 作者:行者123 更新时间:2023-12-01 22:26:01 24 4
gpt4 key购买 nike

我使用这个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);
}

}

如果您在文本字段中输入任何内容,标签将准确显示除最后一个之前的所有内容按下按钮。有什么办法可以解决这个问题吗?谢谢!

最佳答案

只有在通知关键监听器后,文本字段内容才会更改。与其尝试跟踪按键,不如聆听文本字段内容的变化。这可确保您也捕获通过其他方式(例如剪切和粘贴)所做的更改。执行此操作的界面是 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) {
}
});

关于Java Swing JTextField 文本落后一格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28785124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com