首页 > 解决方案 > 使用 FocusListener 从 JTextField 检索内容并填充其他 JTextField

问题描述

我的窗口中有许多组件,其中大部分是 JTextField。为了节省用户输入数据的时间,我尝试在填充时解析第一个 JTextField 的内容,并将建议的值放入后续的 JTextField 中。

我已将 FocusListener 添加到第一个 JTextField,并在 focusLost() 中检索其内容,然后设置后续 JTextField 的内容。这在第一次使用应用程序时可以正常工作。然而,在后续任务中(即在处理完所有数据并清除字段之后)它通常(但不总是)失败。焦点问题的调试很困难,所以我改用日志记录,可以看到在失败的情况下,第一个 JTextField 上的 getText() 方法返回 null。这一定是时间问题,但我看不到解决方法。

focusLost() 方法开始...

@Override
public void focusLost(FocusEvent e) {
    // On losing focus of the title field attempt to populate all the other
    // resource detail fields
    Component rawComponent = e.getComponent();
    if (this.resourceTitleTextField == rawComponent) {

        JTextField component = (JTextField) rawComponent;
        String title = component.getText();
        LOGGER.info("title = " + title);

标签: javaswingjtextfieldfocuslistener

解决方案


推荐阅读