JTextField上的FocusListener无法正常工作

时间:2013-10-24 22:25:42

标签: java swing focuslistener

我创建了一个使用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();
}

}

2 个答案:

答案 0 :(得分: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以获取更多想法

答案 1 :(得分:1)

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

相关问题