【问题标题】:FocusListener on JTextField not workingJTextField 上的 FocusListener 不起作用
【发布时间】:2013-11-03 20:44:23
【问题描述】:

我创建了一个应用程序,它使用 FocusListener 来确保文本字段的值始终为正。当用户输入负值,然后单击“制表符”键将焦点从文本字段移开时,该值将乘以 -1,因此结果值为正值。但是,当我运行应用程序时,文本字段并没有改变。我不确定我做错了什么,如果有任何帮助,我将不胜感激。

这是我的代码:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class AlwaysPositive extends JFrame implements FocusListener {
JTextField posField = new JTextField("30",5);

public AlwaysPositive() {
    super("AlwaysPositive");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel pane = new JPanel();
    JTextField posField = new JTextField("30",5);
    JButton ok= new JButton("ok");
    posField.addFocusListener(this);
    pane.add(posField);
    pane.add(ok);
    add(pane);
    setVisible(true);
}

public void focusLost(FocusEvent event) {
    try {
        float pos = Float.parseFloat(posField.getText());
        if (pos < 0) 
            pos = pos*-1;
        posField.setText("" + pos);
    } catch (NumberFormatException nfe) {
        posField.setText("0");
    }
}

public void focusGained(FocusEvent event) {
}

public static void main(String[] arguments) {
    AlwaysPositive ap = new AlwaysPositive();
}

}

【问题讨论】:

    标签: java swing focuslistener


    【解决方案1】:

    主要问题是你隐藏了你的变量

    你声明

     JTextField posField = new JTextField("30",5);
    

    作为一个实例变量,但是在你的构造函数中,你又重新声明了它...

    public AlwaysPositive() {
        //...
        JTextField posField = new JTextField("30",5);
        posField.addFocusListener(this);
        //...
    }
    

    将焦点监听器添加到它,但在focusLost 方法中,您指的是实例变量,它不是实际在屏幕上的那个

    从改变构造函数中的声明开始

    public AlwaysPositive() {
        //...
        posField = new JTextField("30",5);
        posField.addFocusListener(this);
        //...
    }
    

    但是,还有比FocusListener 更好的解决方案。

    例如,您可以使用InputVerifier,它允许您验证字段的值并决定是否应该移动焦点。

    尤其是How to Use the Focus SubsystemValidating Input

    您还可以使用DocumentFilter 来限制用户实际可以输入的内容,在用户键入时过滤输入。尤其是Text Component FeaturesImplementing a Document Filter

    您也可以查看these examples 了解更多想法

    【讨论】:

    • 今天,我解释了InputVerifier here 的一个问题。尽管问题不在于验证者,而在于底层用例和设计。你介意看看吗?
    • 非常感谢您的详细解释!
    【解决方案2】:

    当您在方法中创建同名对象时,侦听器将设置为方法对象而不是 Class 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-21
      • 2012-09-24
      • 2011-01-17
      • 1970-01-01
      • 2013-12-17
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多