Java TextField getText() 返回先前的字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6591141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:01:29  来源:igfitidea点击:

Java TextField getText() returns previous string value

javaswingtextfield

提问by PlodPla

I have a problem with Java Textfield that is when I cover all text in the JTextField and input new text immediately(do not pass backspace) into the JTextField, then I use function getText() I get the previous string not current string. Please help for some solutions. Thanks in advance.

我有一个 Java Textfield 的问题,即当我覆盖 JTextField 中的所有文本并立即将新文本(不要通过退格键)输入到 JTextField 中时,然后我使用函数 getText() 我得到的是前一个字符串而不是当前字符串。请帮助一些解决方案。提前致谢。

采纳答案by Adam Smith

I just tested the problem you described by adding a keyListener to a JTextField and printing the getText() method's return value to the console.

我刚刚通过向 JTextField 添加 keyListener 并将 getText() 方法的返回值打印到控制台来测试您描述的问题。

What I found out is that it is always one character behind if you want to use the getText() method right in the keyTyped or keyPressed event (I didn't know this because I usually just use a button to confirm I'm done entering the text and bind a KeyEvent to the Return key to trigger the button if a user wants to confirm by hitting enter)

我发现如果你想在 keyTyped 或 keyPressed 事件中使用 getText() 方法,它总是落后一个字符(我不知道这一点,因为我通常只使用一个按钮来确认我已经完成输入文本并将 KeyEvent 绑定到 Return 键以触发按钮(如果用户想通过按 Enter 确认)

I think this is due to the textField updating its text value AFTER the event is shot.

我认为这是由于在事件发生后 textField 更新了其文本值。

I assume this is what you did since you didn't provide sample code, so I'll delete this answer if it's not.

我认为这是您所做的,因为您没有提供示例代码,所以如果不是,我将删除此答案。

The work around to this is to implement what you want to do in the keyReleased method instead.

解决此问题的方法是在 keyReleased 方法中实现您想要执行的操作。

public void keyReleased(Event e)
{
  System.out.println(myTextField.getText());
}

回答by camickr

Don't use a KeyListener. The character has NOT been added to the Document when the keyPressed() event is fired.

不要使用 KeyListener。当 keyPressed() 事件被触发时,字符还没有被添加到文档中。

Add an ActionListener to a JButton. This way the user clicks on the button when text is finised being entered.

将 ActionListener 添加到 JButton。这样用户在输入文本完成时点击按钮。

Also, in the future post a SSCCEwith you question so we can better understand what you are trying to do.

此外,在未来发布一个SSCCE与您的问题,以便我们可以更好地了解您正在尝试做什么。

回答by mKorbel

for example :

例如 :

import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class TextLabelMirror {

    private JPanel mainPanel = new JPanel();
    private JTextField field = new JTextField(20);
    private JTextField field1 = new JTextField(20);

    public TextLabelMirror() {
        field.getDocument().addDocumentListener(new DocumentListener() {

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

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

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

            private void updateLabel(DocumentEvent e) {
                java.awt.EventQueue.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        field1.setText(field.getText());
                    }
                });
            }
        });

        mainPanel.setLayout(new GridLayout(1, 0, 10, 0));
        mainPanel.add(field);
        mainPanel.add(field1);
    }

    public JComponent getComponent() {
        return mainPanel;
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("TextLabelMirror");
        frame.getContentPane().add(new TextLabelMirror().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowUI();
            }
        });
    }
}